WordPress:カスタムタクソノミーとカスタム投稿のキーワード(タイトル・本文)で絞り込み検索する方法
1特定のカスタム投稿タイプを絞り込み検索
searchform.php
<form role="search" method="get" id="searchform" action="<?php home_url(); ?>/faq" >
<dl>
<dt>質問分類から選ぶ</dt>
<dd>
<input type="hidden" name="serach_for" id="serach_for" value="faq">
<select name="cat">
<option value="">未選択</option>
<?php
if (!empty($_GET['cat'])){
$selected = 'selected';
}
$faq_args = array(
'hide_empty' => false,
);
$faq_posts = get_terms('faq_taxonomy', $faq_args);
if (!empty($faq_posts)): foreach ($faq_posts as $faq_post):
?>
<option <?php if($faq_post->slug == $_GET['cat'] ){ echo $selected; } ;?> value="<?php echo $faq_post->slug; ?>"><?php echo $faq_post->name; ?></option>
<?php endforeach; endif; ?>
</select>
</dd>
</dl>
<dl>
<dt>キーワードから選ぶ</dt>
<dd><input type="taxt" name="s" id="s" value="<?php if(is_search()){ echo get_search_query();} ?>" ></dd>
</dl>
<div class="searchform_btn">
<input id="submit" type="submit" value="検索">
</div>
</form>
2. pre_get_postsで処理
pre_get_posts 設定箇所を下記のように記載。
(1つのタクソノミーで絞り込む場合)
functions.php
add_action( 'pre_get_posts', 'custom_post_archive');
function custom_post_archive($query) {
if (!is_admin() && $query->is_main_query()){
if(is_search()){
$query->set('posts_per_page', -1);
// イベント検索の場合のみ以下
if( $_GET['serach_for'] == 'faq'){
// 変数を取得
$faq_tax = $_GET['cat']; //コース
// 検索条件が指定されている時のみ実行
if($faq_tax){
// タクソノミー設定
if($faq_tax){
$taxquery = array();
$taxquery[] = array(
'taxonomy'=>'faq_taxonomy',
'terms'=> $faq_tax,
'field'=>'slug',
);
}
$query->set( 'tax_query' , $taxquery );
$query->set( 'post_type' , 'faq' );
}
}
}
}
}
3検索後の出力ファイル
search.php
<?php if(have_posts()): while(have_posts()): the_post(); ?> <li class="qa1"><a href="<?php the_permalink() ?>"><?php the_title();?></a></li> <?php endwhile; endif; ?>
参考サイト:
【wordpress】カスタム投稿タイプの検索、タクソノミーでの絞り込み検索