WordPress
カスタマイズ事例

WORDPRESS CUSTOMIZATION

アーカイブページで、ターム(カテゴリ)ごとに分けて記事一覧を表示する テーマ販売あり

いろいろ製品があってそれをカテゴリ、ジャンルごとに分けて一覧表示したい、というニーズは結構あります。
そんなときの解決方法を2つご紹介します。

例としてカスタム投稿タイプを items、カスタム分類名を items_cat としてますので、そのつもりで読み進めてください。

普通にタームごとに記事一覧を表示するバージョン

まず普通バージョンですが、テーマのカスタム投稿アーカイブページ(archive-items.php)の記事一覧(アイキャッチあり)表示部分を次のように記述します。

<?php
// カスタム投稿タイプ
$post_type = 'items';
// カスタム分類名
$taxonomy = 'items_cat';

// パラメータ
$args = array(
	// 親タームのみ取得
	'parent' => 0,
	// 子タームの投稿数を親タームに含める
	'pad_counts' => false,
	// 投稿記事がないタームは取得しない
	'hide_empty' => true
);

// カスタム分類のタームのリストを取得
$terms = get_terms( $taxonomy , $args );

if ( count( $terms ) != 0 ) {
	// 親タームのリスト $terms を $term に格納してループ
	foreach ( $terms as $term ) {

		// 親タームのURLを取得
		$term = sanitize_term( $term, $taxonomy );
		$term_link = get_term_link( $term, $taxonomy );
		if ( is_wp_error( $term_link ) ) {
			continue;
		}

		$slug = $term->slug;

		// 親タームのURLと名称を出力
		echo '<h2><a href="' . esc_url( $term_link ) . '" >' . $term->name . '</a></h2>
			<div>';

		$posts = get_posts( array(
			'post_type' => $post_type,
			'tax_query' => array(
				array(
					'taxonomy' => $taxonomy,
					'field' => 'slug',
					'terms' => $slug
				)
			),
			'posts_per_page' => -1,
		));

		foreach($posts as $post){

			setup_postdata( $post );

			$image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
			$image_url_hon = '';
			if ( $image_url ) {
				$image_url_hon = $image_url[0];
			}
			?>

      <div>
				<?php if ( $image_url_hon ) { ?>
          <a href="<?php the_permalink(); ?>"><img src="<?php echo $image_url_hon; ?>"/></a>
				<?php } ?>
        <p><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
      </div>
<?php

		}
		wp_reset_query();
 ?>
		</div>
	<?php }
} ?>

 
次にプラグイン「Custom Post Type Permalinks」をインストールします。(このプラグインは「どうしてもインストールしておきたいプラグイン10選」でも述べている通り、カスタム投稿で記事を作る方には必須のプラグインだと思ってください。)
 
プラグインのインストールができたら最後にパーマリンクを設定します。
[設定]-[パーマリンク設定]を開き、「items」のカスタム投稿タイプのパーマリンクを以下のように入力します。
/%items_cat%/%post_id%/
 
これで完成です。
これがひとつ目のバージョン。
 
 
次はBootstrapのタブにタームの一覧を表示して、そのタブごとに記事一覧を切り替えてみましょう。

Bootstrapのタブにターム一覧を表示するバージョン

イメージはこんな感じです。
Bootstrapのタブ
このタブのところにタームが表示されるようにします。

テーマのカスタム投稿アーカイブページ(archive-items.php)の記述は以下のようにします。

<?php
// カスタム投稿タイプ
$post_type = 'items';
// カスタム分類名
$taxonomy = 'items_cat';

// パラメータ
$args = array(
  // 親タームのみ取得
  'parent' => 0,
  // 子タームの投稿数を親タームに含める
  'pad_counts' => false,
  // 投稿記事がないタームは取得しない
  'hide_empty' => true
);

// カスタム分類のタームのリストを取得
$terms = get_terms( $taxonomy , $args );

if (count($terms) != 0) {
  $tab_html = '<ul class="nav nav-tabs" id="itemTab" role="tablist">';
  $content_html = '<div class="tab-content" id="itemTabContent">';

  $i = 0;
  // 親タームのリスト $terms を $term に格納してループ
  foreach ($terms as $term) {
    $term_slug = $term->slug;
    $term_name = $term->name;
    $tab_active_html = '';
    $content_active_html = '';
    if ($i == 0) {
      $tab_active_html = 'active';
      $content_active_html = 'show active';
    }
    $tab_html .= '<li class="nav-item">
      <a class="nav-link ' . $tab_active_html . '" id="' . $term_slug . '-tab" data-toggle="tab" href="#' . $term_slug . '" role="tab" 
      aria-controls="' . $term_slug . '" aria-selected="true">' . $term_name . '</a>
    </li>';
    $content_html .= '<div class="tab-pane fade ' . $content_active_html . '" id="' . $term_slug . '" role="tabpanel" aria-labelledby="' . 
    $term_slug . '-tab">';

    $posts = get_posts(array(
      'post_type' => $post_type,
      'tax_query' => array(
        array(
          'taxonomy' => $taxonomy,
          'field' => 'slug',
          'terms' => $term_slug
        )
      ),
      'posts_per_page' => -1,
    ));

    foreach ($posts as $post) {
      setup_postdata($post);
      $image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
      $image_url_hon = '';
      if ( $image_url ) {
        $image_url_hon = $image_url[0];
      }

      $content_html .= '<a href="' . get_permalink() . '">';
      if ($image_url_hon) {
        $content_html .= '<img src="' . $image_url_hon . '"/>';
      }
      $content_html .= get_the_title() . '</a>';
    }
    wp_reset_query();
    $content_html .= '</div>';
    $i++;
  }
  $tab_html .= '</ul>';
  $content_html .= '</div>';

  echo $tab_html;
  echo $content_html;
}
?>
<script>
  $('#itemTab a').on('click', function (e) {
    e.preventDefault()
    $(this).tab('show')
  })
</script>

当然ですがBootstrapのtab機能を使えるようにする必要があるので、
https://getbootstrap.jp/docs/4.5/getting-started/introduction/
などを参考に、Bootstrapのファイルを参照するようにしてくださいね。
 
 
以上、アーカイブページで、ターム(カテゴリ)ごとに分けて記事一覧を表示する方法について、2つご紹介しました。
 
 
※ 本事例では1ページ中で全記事表示してますが、記事数が多い場合などページネーションが必要なケースもあります。
その解決のひとつとして、Ajaxを使ってタームごとに記事をロードする方法を事例として紹介してますので、こちらも参考にしてください。
Ajaxでページネーションなしのターム(カテゴリ)別投稿記事一覧ローディングをつくる

【この事例を解決するためのWordPressテーマを購入できます】

現在あなたが利用されているWordPressテーマを活かしたまま、このページの事例を解決できるWordPressテーマを、子テーマとして購入できます。
この子テーマを有効化するだけで、現在お使いのデザインテーマにこの事例解決の機能が自動付与されます。
デザインが入っていないため、一般より格段に低い価格(事例の難易度により200円~1.3万円)です。
※ テーマは買い切りです
※ 自由に改変してお使いいただいて構いません
※ すでに子テーマでサイト運用されている方は、当該子テーマをマージしてください

【100ウェブ新着情報メルマガ】

WordPressカスタマイズ事例やウェブ制作ノウハウの新着情報、お役立ち情報を
リアルタイムにメルマガ配信!