WordPress

【コピペOK】プラグインなしWordPressで 関連記事 を表示する方法

【コピペOK】プラグインなしWordPressで 関連記事 を表示する方法のアイキャッチ画像

こんにちは、キムゴンです。

今回はプラグインなしでWordPressに関連記事を表示させてみました。

コピペで導入可能なので未導入の方は試してみてください。

関連記事 とは

関連記事 とは以下のようなもので、記事の最後に記載することが一般的です。

私のサイトの 関連記事

関連記事 は読者のサイト巡回率を向上させる目的で導入されます。

Youtubeの 関連動画 をイメージして頂くとわかりやすいと思います。

ついつい、他の動画も見てしまいますよね。

PHPコード

・function.phpに追記

こちらはfunction.php内のどこでも良いので追記してください。

function codeless_get_related_posts( $post_id, $related_count, $args = array() ) {
  $terms = get_the_terms( $post_id, 'category' );
  
  if ( empty( $terms ) ) $terms = array();
  
  $term_list = wp_list_pluck( $terms, 'slug' );
  
  $related_args = array(
    'post_type' => 'post',
    'posts_per_page' => $related_count,
    'post_status' => 'publish',
    'post__not_in' => array( $post_id ),
    'orderby' => 'rand',
    'tax_query' => array(
      array(
       /*同じカテゴリーの関連記事を表示させます*/
        'taxonomy' => 'category',
        'field' => 'slug',
        'terms' => $term_list
      )
    )
  );
  return new WP_Query( $related_args );
}

・single.phpに追記

こちらはsingle.phpの最後に追記してください。

私はbootstrapを使用していますが、未使用の方はレスポンシブ対応はご自身でお願いします。

<?php
  $the_query = codeless_get_related_posts( get_the_ID(), 4 );
	global $cl_from_element;
	$cl_from_element['is_related'] = true;						
	if ( $the_query->have_posts() ) : 
?>
<div class="container">
  <div class="row related_posts">
	  <h3><?php echo esc_attr__( '関連記事' ) ?></h3>
		<?php $i = 0;
			while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
		<div class="col-xs-12 related_post">
			<a href="<?php the_permalink(); ?>">
				<div class="related_thumb">
					<?php the_post_thumbnail('medium'); ?>
				</div>
				<p class="related_title">
					<?php the_title(); ?>
				</p>
			</a>
		</div>
		<?php	
			$i++;
			if( $i == 4 )
			break;
			endwhile ;?>	
		<?php endif; 
			wp_reset_query();
			$cl_from_element['is_related'] = false;
		?>
	</div>
</div>

この2つで外観は完成しました。

レイアウト調節前の 関連記事

もう少し全体レイアウトを整えていきましょう。

CSSコード

.related_posts h3{
	margin-bottom: 30px;
}

.related_post {
	 border: 1px solid #F1F2F4;
    margin-bottom: 5%;
    margin-right: 2%;
    margin-left: 2%;
    padding-bottom: 20px;
	 text-align: center;
}

.related_thumb {
	margin-top: 30px;
	margin-bottom: 30px;
}

.related_thumb img {
	object-fit: fill;
	width: 95%;
	height: 200px;
}


@media screen and (min-width:768px) {
	.related_post {
	 width: 46%;
  }
}

このCSSを導入すると冒頭でも見せたレイアウトになります。

<完成>

私のサイトの 関連記事

今回は完全コピペで導入できる 関連記事欄の作成方法についてまとめました。

関連記事 があるだけでサイトに彩りが出ますね。

今回は完全コピペで導入できることから、あえて細かいPHPについて解説していません。

上手く導入できない場合、バージョンアップ等により仕様が変更し使えなくなった場合は twitterお問い合わせ で連絡していただければ返答いたします。

それでは、みなさん、良い1日を!

参考

How to add WordPress Related Posts without a Plugin 2021

この記事をシェアする:

-WordPress