プラグインなしでWordPressの記事内にタグで分類された関連記事を表示させる

WORDPRESS

2019.04.23

2019.04.24

プラグインなしでWordPressの記事内にタグで分類された関連記事を表示させる

WordPressの投稿記事内に、プラグインをつかわずに関連記事を表示させる方法を紹介します。プラグインを使わなくても非常に簡単に設置出来るのでおすすめです。なお、今回はカテゴリではなく、タグで分類された関連記事の表示方法になります。

サムネイルも一緒に取得して表示させる方法、記事タイトルのみを表示させる方法を書いていますので、デザイン、好みに合わせて使い分けてもらえればと思います。

実装方法

サムネイルも表示させる場合

single.phpの任意の場所に下記を記述します。「’showposts’=>4,」という部分で表示する記事の数を4つと制御しています。

<ul>
<?php
    $original_post = $post;
    $tags = wp_get_post_tags($post->ID);
    $tagIDs = array();
    if ($tags) {
        $tagcount = count($tags);
        for ($i = 0; $i < $tagcount; $i++) {
            $tagIDs[$i] = $tags[$i]->term_id;
        }
    $args=array(
    'tag__in' => $tagIDs,
    'post__not_in' => array($post->ID),
    'showposts'=>4,
    'ignore_sticky_posts'=>1
    );
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
    while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <li>
         <span class="cat-thum">
           <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>の詳細へ"><?php
           if ( has_post_thumbnail()) {
                the_post_thumbnail('thumbnail');
               } else {
              echo '<img src="'.get_bloginfo('template_url').'/images/no-image.gif" alt="hoge" />';
              };
           ?></a>
         </span>
            <h4>
                <a href="<?php the_permalink();?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
            </h4>
        </li>
<?php endwhile; wp_reset_query(); ?>
	</ul>
<?php } else { ?>
    関連する記事は見当たりません
<?php } } ?>

記事タイトルのみを表示させる場合

サムネイルまで表示させる必要が無い場合は、こちらをお使いください。

<ul>
<?php
    $original_post = $post;
    $tags = wp_get_post_tags($post->ID);
    $tagIDs = array();
    if ($tags) {
        $tagcount = count($tags);
        for ($i = 0; $i < $tagcount; $i++) {
            $tagIDs[$i] = $tags[$i]->term_id;
        }
    $args=array(
    'tag__in' => $tagIDs,
    'post__not_in' => array($post->ID),
    'showposts'=>4,
    'ignore_sticky_posts'=>1
    );
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
    while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <li>
            <h4>
                <a href="<?php the_permalink();?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
            </h4>
        </li>
<?php endwhile; wp_reset_query(); ?>
</ul>
<?php } else { ?>
    関連する記事は見当たりません…
<?php } } ?>
最近チェックした商品

プラグインなしでWordPressの記事内にタグで分類された関連記事を表示させる