我試圖在使用AJAX顯示帖子和自定義帖子類型的Wordpress中創建搜索功能。到目前爲止,我已經設法讓所有事情都能按照我的想法工作,但搜索使用高級自定義字段輸出的內容不會顯示在AJAX結果中。包含來自高級自定義字段的數據的Ajax搜索功能
例如;我知道在我的一篇文章中提到了「Skittles」,但當我搜索「Skittles」時,在AJAX結果中找不到任何內容。但是,如果我點擊「輸入」並最終顯示在單獨的搜索結果頁面上,則會發現包含「Skittles」一詞的帖子,但這不是我想要的行爲。
下面的代碼使自定義字段成爲可搜索的。結果顯示在Wordpress自己的搜索結果頁面上。
/**
* Finds custom fields meta data in search results
* http://adambalee.com
*/
function cf_search_join($join) {
global $wpdb;
if (is_search()) {
$join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
}
return $join;
}
add_filter('posts_join', 'cf_search_join');
function cf_search_where($where) {
global $wpdb;
if (is_search()) {
$where = preg_replace(
"/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where);
}
return $where;
}
add_filter('posts_where', 'cf_search_where');
function cf_search_distinct($where) {
global $wpdb;
if (is_search()) {
return "DISTINCT";
}
return $where;
}
add_filter('posts_distinct', 'cf_search_distinct');
但我不希望人們在WordPress的自己的搜索結果頁面中結束。
這是我使用的AJAX搜索代碼:
/**
* Adding ajax search functionality to the theme
* @return
*/
function dhemy_ajax_search() { // creating a search query
$args = array(
'post_type' => array('case', 'post'),
'post_status' => 'publish',
'order' => 'DESC',
'orderby' => 'date',
's' => $_POST['term'],
'posts_per_page' => 9999
);
$query = new WP_Query($args);
if($query->have_posts()) { // display results
while ($query->have_posts()) { $query->the_post(); ?>
<?php if(get_post_type() == 'case') { ?>
<?php // code output for the cpt called 'case' ?>
<?php } else { ?>
<?php // code output for regular posts ?>
<?php } ?>
<?php }
} else { ?>
<?php // code output for when there are no hits ?>
<?php } exit;
}
add_action('wp_ajax_nopriv_dhemy_ajax_search', 'dhemy_ajax_search');
add_action('wp_ajax_dhemy_ajax_search', 'dhemy_ajax_search');
使用JavaScript一起:
$('#bigsearch').keyup(function(event) {
var searchTerm = $(this).val(); // get search term
if(!searchTerm.trim()) {
$('.search_overlay .flow .wrap .post_row').html('');
return;
}
else if(searchTerm.length > 0) { // send request when the lenght is greater than 0 letters
$.ajax({
url: BASE+'/wp-admin/admin-ajax.php',
type: "post",
data: {
'action':'dhemy_ajax_search',
'term':searchTerm
},
success: function(result) {
$('.search_overlay .flow .wrap .post_row').fadeIn().html(result);
}
});
}
});
是否有可能包括來自WP_query
的$args
自定義字段中的數據?或者是否可以將第一個功能與實際的搜索功能結合起來?