Steamer Lane Studio技術備忘録ワードプレス

WordPress投稿タグによる複数タグ絞り込み検索

wordpress WordPress投稿タグによる複数タグ絞り込み検索
最終更新日: 2023年4月15日

ポータルサイト案件から。
タグクラウド的なものを造り、そのチェックボックスを複数選択し検索結果を表示するものだが、拘ったのはその検索文字列をURLに合わせるところ。
これは以前MovableType案件だがMTの動的検索結果表示が検索上位表示されたことから、そのタグをキーワードに引っける格好にしたもので、流用でmetaタグなどにも用いてSEO対策としたもの。
MTの動的検索結果はサーバーサイドスクリプトによるもので、こちらのURLはjavaで作るのでなんだがね、Googleさんがどんな判断するか。要jQuery、ver2以上なら動くんじゃないかな。

<?php //一覧表示自動
$taxonomy_name = 'post_tag';
$taxonomys = get_terms($taxonomy_name);
if(!is_wp_error($taxonomys) && count($taxonomys)):
foreach($taxonomys as $taxonomy):
if ( in_array( $taxonomy->slug, array( 'komuro', 'misaki' ) ) ) continue;
$tax_posts = get_posts(array('post_type' => get_post_type(), 'taxonomy' => $taxonomy_name, 'term' => $taxonomy->slug ) );
if($tax_posts):
?>
<label style="font-size:1rem;"><input type="checkbox" class="checks" name="posttag" value="<?php echo $taxonomy->slug; ?>"><?php echo $taxonomy->name; ?></label>
<?php endif; endforeach; endif;?>
<button type="submit" id="button5" class="search-submit">選択した条件で検索する</button>
<script>
jQuery(function() {
$("#button5").click(function() {
let res = '';
//確認用box p5というクラスの入れ子を作るもちろんp5である必要はない。 $('.p5').text(res);
$('input:checkbox[name="posttag"]:checked').each(function() {
res += $(this).val() + '+';
var resstr = res.slice(0, -1) ;
location.href= "<?php echo esc_url( home_url( '/' ) ); ?>tag/" + resstr;//このlocation.hrefでURLにタグ(日本語可)をURL表示させる
});
});
});
</script>