0 レビュー
1 回答
php-カスタム投稿タイプでもWordpressajax検索
「accelerate」という投稿タイプがあり、その投稿タイプには、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検索を行うにはどうすればよいですか?
わからない
0
レビュー
答え :
解決:
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
}
わからない
同様の質問
私たちのウェブサイトで同様の質問で答えを見つけてください。