我在Wordpress中有一个搜索表单,它可以搜索自定义帖子类型中的所有帖子标题,内容和自定义字段。它不会被作者搜索。我希望搜索关键字与显示名称匹配,并输出该作者的任何帖子。通过MySQL查询获取WordPress的用户显示名称的帖子
这是我目前的代码(它的display_name部分显然是错误的,但说明了我想完成的)。除了通过display_name部分获取帖子之外,一切都有效。任何帮助或指导表示赞赏:)
// Code originally modified
// from http://www.deluxeblogtips.com/2012/04/search-all-custom-fields.html
global $wpdb;
// Gets the ?crs= search from the submitted form
$keyword = sanitize_text_field($_GET['crs']);
$keyword = '%' . like_escape($keyword) . '%';
// Search in all custom fields
$post_ids_meta = $wpdb->get_col($wpdb->prepare("
SELECT DISTINCT post_id FROM {$wpdb->postmeta}
WHERE meta_value LIKE '%s'
", $keyword));
// Search in post_title and post_content
$post_ids_post = $wpdb->get_col($wpdb->prepare("
SELECT DISTINCT ID FROM {$wpdb->posts}
WHERE post_title LIKE '%s'
OR post_content LIKE '%s'
", $keyword, $keyword));
// Search in User Table for Display Name
// This is where I'm not sure what how to get the posts by display_name
$post_ids_user = $wpdb->get_col($wpdb->prepare("
SELECT DISTINCT post_id FROM {$wpdb->users}
WHERE display_name LIKE '%s'
", $keyword));
$post_ids = array_merge($post_ids_meta, $post_ids_post, $post_ids_user);
// Query arguments for WP_Query
$args = array(
'post_type' => 'courses',
'post_status' => 'publish',
'limit' => '',
'post__in' => $post_ids,
);
据我所知,据我所知,应该写成'%% keyword %%'。 ** %% **是转义序列,并被解析为**%**。 '$ wpdb-> prepare'会正确解析它。这是第一眼看到的。 – Rolice
你是指这一部分?我不确定你指的是什么或为什么它有帮助。对不起,我的知识缺乏:) '$ post_ids_user = $ wpdb-> get_col($ wpdb-> prepare(“ SELECT DISTINCT post_id FROM {$ wpdb-> users} WHERE display_name LIKE'%s' ”, $关键字));'' – Jerry