🏡まったのブログ

カスタム投稿タイプのアーカイブページをカスタムフィールドとカスタムタクソノミーの値で絞り込んで表示する

カスタム投稿タイプ「discography」に、カスタムタクソノミー 「discography_type」を追加し、更にカスタムフィールド「artist」に値を設定することで「あるアーティストのシングルの作品だけを一覧表示したい」というニーズがありました。

理想としては、今いるアーティストページにある以下のようなリンクを踏んで、該当する作品一覧を表示させたい訳です。

<a href="/discography/?my_artist=<?php echo $post->ID; ?>&my_discography_type=single">すべてのシングル作品をみる</a>

URLクエリを渡すためにカスタムクエリ変数を追加する

先のようなURLに?my_artsit=hogeのようなクエリーを付けるだけでは遷移先のページで取得はできないので、functions.phpに以下を記述。

// functions.php にカスタムクエリ変数を追加
function add_query_vars_filter( $vars ){
  $vars[] = [
		"my_artist",
		"my_discography_type"
	];
  return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );

これで$_GET['クエリー変数名']でURLクエリーの値を取得できるようになります。

<?php
$my_artist = $_GET['my_artist'];
$my_discography_type = $_GET['my_discography_type'];
?>

カスタムタクソノミー とカスタムフィールドで絞り込む

// archive-discography.php
<?php
$my_artist = $_GET['my_artist'];
$my_discography_type = $_GET['my_discography_type'];
?>

// 中略
      $args = array(
        'post_type' => 'discography', // 投稿タイプを指定
        'tax_query' => array( // タクソノミーを指定
          array(
            'taxonomy' => 'discography_type',
            'field' => 'slug',
            'terms' => $my_discography_type,
          ),
        ),
        'meta_query' => array( // カスタムフィールドの値を指定
          array(
            'key' => 'artist',
            'value' => $my_artist,
            'compare' => 'IN',
          ),
        ),
      );

    $my_query = new WP_Query( $args );
    if ($my_query->have_posts()) :
        while ( $my_query->have_posts() ) : $my_query->the_post(); ?>

           <?php get_template_part('loop'); // ここはテーマによって変わる ?>

       <?php endwhile; wp_reset_postdata();  ?>
    <?php endif; ?>

参考リンク

https://rensrv.com/wp/query_string_add/#wordpressurl
https://sachips.byeto.jp/wordpress/wp-customfield-wpquery.html
https://ghweb.info/post-3685.html