ajaxを使ったタグによる検索と結果

function.php内に以下のように追加する

/*
/タグによる検索
*/
function get_tag_list(){

$ctgid = $_POST[‘ctgid’];//postで受け取るカテゴリーID
$ctgname = $_POST[‘ctgname’];//postで受け取るカテゴリー名
$ctgslug = $_POST[‘ctgid’];//postで受け取るカテゴリーID=スラッグ名
$posttype = $_POST[‘posttype’];//postで受け取るカスタムポストタイプ名

$args = array(

‘numberposts’ => -1, //表示する記事の数
‘post_type’ => $posttype, //投稿タイプ名
‘orderby’ => ‘rand’,
‘tax_query’ => array(

array(

‘taxonomy’ => $posttype.’_tag’,
‘field’ => ‘slug’,
‘terms’ => $ctgslug

)

)

);

$customPosts = get_posts($args);

if($customPosts) :

foreach($customPosts as $post) : setup_postdata( $post );

//work content
$img = get_field(‘rs-photo1’,$post->ID);

//$imgurl = array();
$imgurl = wp_get_attachment_image_src($img, $post->ID, ‘medium’);

//出力html配列の内容
$outhtml[] = array(

“categoryname” => $ctgname,
“categoryslug” => $ctgslug,
“alllists” => ”,
“id” => $post->ID,
“title” => get_the_title($post->ID),
“workimage” => $imgurl[0],
“worktext” => get_field(“rs-comment”,$post->ID),
“areaname” => get_field(“rs-area”,$post->ID),
“parmalink” => get_the_permalink($post->ID),

);

endforeach;

else:

$outhtml[] = array(

“categoryname” => ”,
“categoryslug” => ”,
“alllists” => ”,
“id” => ”,
“title” => ‘データはありませんでした。’,
“workimage” => ‘https://www.mysite.jp/wp/wp-content/uploads/2017/12/mysite_noimage.jpg’,
“worktext” => ”,
“parmalink” => ”,
“areaname” => ”,

);

endif;

//JSON形式で返す

echo json_encode($outhtml, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);

wp_reset_postdata();

die();

}

add_action( ‘wp_ajax_get_tag_list’, ‘get_tag_list’ );
add_action( ‘wp_ajax_nopriv_get_tag_list’, ‘get_tag_list’ );