Wordpress ajax搜索也在自定义帖子类型中



我有一个名为"accept"的帖子类型,在该帖子类型中,我有一种名为inspiration的自定义字段(文本字段(。

我还有一个ajax搜索,可以在打字时显示帖子。

jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});

和这个php函数查询:

function data_fetch() {
$the_query = new WP_Query( array( 
'posts_per_page' => -1, 
's' => esc_attr( $_POST['keyword'] ), 
'post_type' => 'accelerate'
) );
$the_second_query = new WP_Query( array ( 
'posts_per_page' => -1, 
'post_type' => 'accelerate',
'meta_key' => 'inspiration',
'meta_value' => esc_attr( $_POST['keyword'] ),
));
$the_query->posts = array_merge( $the_query->posts, $the_second_query->posts );
if( $the_query->have_posts() ) : ?>
...output html
<?php endif; ?>

预期行为是在帖子和灵感自定义字段中搜索,但后者不是真的。

我如何在帖子和它的自定义字段中进行ajax搜索?

您可以像下面的一样在WP_query中使用meta_query参数

function data_fetch() {
$the_query = new WP_Query(array( 
'posts_per_page' => -1, 
's' => esc_attr($_POST['keyword']), 
'post_type' => 'accelerate'
));
$the_second_query = new WP_Query(array( 
'posts_per_page'    => -1, 
'post_type'     => 'accelerate',
'meta_query' => array(
'relation' => 'OR',
array(
'key'       => 'inspiration',
'value'       => esc_attr($_POST['keyword']),
'compare' => 'IN'
)
),
));
$the_query->posts = array_merge($the_query->posts,$the_second_query->posts);
if($the_query->have_posts()){ ?>
...output html
<?php
}

最新更新