LoginSignup
10
9

More than 5 years have passed since last update.

【WordPress】同じタグを持つ記事を関連記事として表示する方法

Posted at

【WordPress】同じタグを持つ記事を関連記事として表示する方法

関連記事を表示する方法としてタグを使用して実現するやり方をメモ

・記事本文の下部に関連記事を表示してみる。
以下は実装前の状態。
before記事_.png

・まず、こんな感じでタグを作成。

tag画面.png

・次に、こんな感じでタグをつけた記事を作成。
記事タグ.png

・個別ページ記事を表示するテンプレートに以下のように関連記事を抽出するロジックを実装・

single.php
〜〜本文を出力している箇所〜〜

    $current_tags = get_the_tags();
    //この記事がタグを持っているかどうか判別
    if ( $current_tags ) :
        foreach ( $current_tags as $tag ) {
            $current_tag_list[] = $tag->term_id;
        }

        $args = array(
            'tag__in'        => $current_tag_list,
            'post__not_in'   => array( $post->ID ),
            'posts_per_page' => 5,
        );
        $related_posts = new WP_Query( $args );
         //関連する記事があるかどうか判別
        if( $related_posts->have_posts() ) :
            ?>
            <h3>関連記事</h3>
            <ul id="related-test">
                <?php
                //関連する記事を表示
                while ( $related_posts->have_posts() ) :
                    $related_posts->the_post();
                    ?>
                    <li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
                    <?php
                endwhile;
                ?>
            </ul>
            <?php
        else :
            //関連記事がなければ以下を表示
        ?>
        <p>関連記事はありません</p>
        <?php
        endif;
        wp_reset_postdata();
endif;

〜〜コメント出力箇所〜〜

・記事を表示すると、同じタグを持った記事が関連記事として表示されるようになりました!
記事1_.png

記事2−2_.png

10
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9