我在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