今回は、single.phpに、関連する記事(その記事自体は省いたもの)を表示させる方法です。
記事の下に表示させることが多いです。
その記事が所属するタームから、記事をランダムで3件表示させます。
目次
コード
<?php $terms = get_the_terms($post->ID,'custom-post-taxonomy'); foreach( $terms as $term ) { $term_slug = $term->slug; // 現在表示している投稿が所属しているタームを取得 } $args = array( 'post_type' => 'custom-post', // 投稿タイプ名 'post__not_in' => array($post->ID), // 現在表示している投稿を除外 'posts_per_page' => 3, // 表示件数 'orderby' => 'rand', // ランダム表示 'tax_query' => array( array( 'taxonomy' => 'custom-post-taxonomy', // タクソノミー名 'field' => 'slug', 'terms' => $term_slug, // 取得したタームを指定 )) ); $the_query = new WP_Query($args); if($the_query->have_posts()): ?> <div> <ul> <?php while ($the_query->have_posts()): $the_query->the_post(); ?> <li> <article> <a href="<?php the_permalink() ?>"> <?php if( has_post_thumbnail() ): ?> <?php the_post_thumbnail(); ?> <?php else: ?> <img src="<?php bloginfo('template_url'); ?>/images/common/noimage.png" alt="" /> <?php endif; ?> <div> カテゴリー: <?php if ($terms = get_the_terms($post->ID, 'custom-post-taxonomy')) { foreach ( $terms as $term ) { echo '<span>' .$term->name. '</span>'; } } ?> </div> <div><?php the_time('Y.m.d'); ?></div> <div><?php the_title(); ?></div> </a> </article> </li> <?php endwhile; ?> </ul> </div> <?php wp_reset_postdata(); ?> <?php endif; ?>
カテゴリーの表示に関する部分はこちらの記事を参照してください。
カスタム投稿タイプのsingle.phpで、所属するカテゴリーを複数表示する(リンクなし、リンクあり)
出力結果
<div> <ul> <li> <article> <a href="xxx"> <img src="xxx.png" alt=""> <div> カテゴリー: <span>カテゴリーテスト</span><span>カテゴリーテスト2</span> </div> <div>2021.04.16</div> <div>記事タイトル</div> </a> </article> </li> ~省略 </ul> </div>
コメント