WordPressのカテゴリーアーカイブをタグで絞り込み検索

カテゴリーアーカイブのぺージ上で、カテゴリー×タグの絞り込み検索を実装したメモです。

検索結果ぺージに投げるパターンはよくありますが、カテゴリーアーカイブのページ上でタグを使って絞り込みを実行する方法をやってみました。

検索結果ページとカテゴリーアーカイブで表示内容やデザインを変えている場合などで使える実装かと思います。少し変えると、カスタムタクソノミーでも利用可能です。

  1. フォーム
  2. 表示

フォーム

if( is_category() ){
	$cat_id = get_query_var( 'cat' );
	$url = get_category_link( $cat_id );
	$post_ids = get_objects_in_term( $cat_id, 'category' );
	$args = array(
		'orderby'		=> 'count', 
		'order'			=> 'DESC',
		'object_ids'	=> $post_ids,
	);
	$terms = get_terms( 'post_tag', $args );

	if ( ! empty( $terms ) && !is_wp_error( $terms ) ){
?>
<div class="filter-archive">
	<form action="<?php echo $url; ?>"  class="filter-archive_form">
		<select name="filter_tag">
			<option value="">---</option>
			<?php
			$filter_tag = get_filter_tag();
			foreach ( $terms as $term ) {
				$selected = $filter_tag == $term->term_id ? ' selected' : '';
				echo '<option value="' . $term->term_id . '"' . $selected . '>' . $term->name . '</option>';
			}
			?>
		</select>
		<input type="submit" value="絞り込む">
	</form>
</div>
<?php
	}
}

ポイント

  • カテゴリーの記事が利用しているタグだけに絞り込み(get_objects_in_term()で取得したidの配列をget_terms()object_idsに渡す)
  • get_filter_tagは自作関数(下記参照)

表示

if( !empty( $_GET['filter_tag']) ){
	$term_id = get_filter_tag();
	if( $term_id ){
		add_action( 'pre_get_posts', 'filter_archive' );
	}
}

function get_filter_tag(){
	$term_id = '';
	if( !empty( $_GET['filter_tag']) ){
		$term_id = (int)$_GET['filter_tag'];
	}
	return $term_id;
}

function filter_archive( $query ){
	if( !is_admin() && $query->is_main_query() ){
		$term_id = get_filter_tag();
		$query->set( 'tag_id', $term_id );
	}
}

ポイント

  • pre_get_postsにフックしてクエリを取得する前に条件を変更
  • $query->set( 'tag_id', $term_id )で絞り込み条件となる term_id を渡す

サポートが必要ですか?

ご質問・お見積り依頼はお気軽にどうぞ

お問い合わせはこちら
シェア
野良人 代表
新免祥太
1988年岡山生まれ。外食企業のWEB・EC担当を経験したのち、2013年12月より「野良人(のらんど)」の屋号で独立しWEBデザイン・プログラミングなどWEBサイト制作の工程全般を請け負っています。お気軽にご相談ください。
広告
次の記事(2022/05/09)
Stripe カスタマーポータルの導入
前の記事(2022/01/29)
WordPressでのAjax実装方法
記事一覧