WordPress

WordPress|プラグインを使わず関連記事をページ下部に表示

関連記事を投稿ページの下部に表示したい場合、プラグインを使用すれば簡単に実現できますが、利用しているテーマやプラグインとの相性の問題でうまく表示されない場合もあるので、今回は自作で実現する方法を紹介します。

今回紹介する方法を適用すると、下記のように関連記事が表示されるようになります。

single.php にコード追加

今回は投稿ページに関連記事を追加するので、single.php にコードを追加します。このコードの特徴は下記のとおりです。

  • 表示中の投稿と同じカテゴリに属している記事を取得(複数カテゴリ対応)
  • 関連記事からランダムで4件を取得して表示(パラメータで変更可能)
  • 「トップに固定」した投稿は無視(パラメータで変更可能)
  • 表示中の記事にカテゴリが登録されていない場合、同じカテゴリの記事がない場合は何も出力しない

single.php 内の関連記事を表示したい場所に下記のコードを追加します。

single.php(…/wp-content/themes/テーマフォルダ/single.php)
<?php if( has_category() ) : //表示中の投稿に登録されているカテゴリがある場合のみ下記実行 ?>
<?php
//表示中の投稿に登録されているカテゴリID(term_id)を全て取得
$categories = get_the_category();
$cat_term_ids = array();
foreach($categories as $category){
	$cat_term_ids[] = $category->term_id; //cat_ID でも同じ
}

//関連記事取得用クエリパラメーター
$args = array(
	'post_type' => 'post',	//投稿を指定 (固定ページの場合は 'page')
	'posts_per_page' => '4',	//取得する件数
	'ignore_sticky_posts' => true,	//「トップに固定」した投稿は除く
	'post__not_in' => array( $post->ID ),	//除外する投稿(本記事)
	'category__in' => $cat_term_ids,	//対象となるカテゴリID(配列)
	'orderby' => 'rand'	//表示順をランダムにしてい(日付順の場合は 'date')
	);
$the_query = new WP_Query( $args );	//クエリ実行
?>

<?php if( $the_query->post_count > 0 ) : //該当する投稿が1件以上あったら下記出力 ?>
<aside class="relPostWrap">
	<h5>関連記事</h5>
	<ul>
		<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
			<li>
				<div class="thumb">
					<span class="post_date"><?php the_date('Y/n/j'); ?></span>
					<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('medium'); ?>
				</div>
				<div class="title"><?php echo wp_trim_words(get_the_title(), 48, "…", "UTF-8"); ?></div>
			</a></li>
		<?php endwhile; ?>
		<?php wp_reset_postdata(); ?>
	</ul>
</aside>
<?php endif; // end of "if( $the_query->post_count > 0 )" ?>
<?php endif; // end of "if( has_category() )" ?>

参考までに、クエリ パラメータを変更すれば、様々な条件で投稿情報を取得できます。たとえば、表示中の記事と同じ投稿者の関連記事を取得したい場合は、'author__in' => $post->post_author を追加します。

$args = array(
	'post_type' => 'post',
	'posts_per_page' => '4',
	'ignore_sticky_posts' => '1',
	'post__not_in' => array( $post->ID ),
	'category__in' => $cat_term_ids,
	'author__in' => $post->post_author, //現在表示中の記事の記者を指定
	'orderby' => 'rand'
	);

クエリの種類やその説明については下記のサイトを参考にしてください。

関数リファレンス/WP Query |  WordPress Codex
https://wpdocs.osdn.jp/.../WP_Query

css にコード追加

上のコードで出力したHTMLのデザインを整えるため、下記のコードをCSSファイルに追記します。希望に応じて適当に変更してください。

style.css
.relPostWrap {
	margin: 50px 0;
	padding: 10px;
	background-color: #fafafa;
	overflow: hidden;
}
	/* 関連記事メインタイトル */
	.relPostWrap h5 {
		margin: 0;
		margin-top: 0.5em;
		text-align: center;
		font-size: 2em;
		color: #bfbfbf;
	}
	.relPostWrap ul {
		margin: 30px 0 0 10px;
		list-style: none;
		display: flex;
		flex-wrap: wrap;
		justify-content: start;
	}
		.relPostWrap li {
			padding: 0;
			margin: 0;
			width: calc(25% - 4px);
			margin-left: 2px;
			margin-right: 2px;
			position: relative;
		}
	/* 記事サムネイル ラップ */
	.relPostWrap div.thumb {
		position: relative;
	}
		/* 記事投稿日 */
		.relPostWrap div.thumb span.post_date {
			display: inline-block;
			padding: 4px 6px;
			line-height: 1em;
			position: absolute;
			background-color: rgba(0, 0, 0, 0.3);
			bottom: 2px;
			right: 2px;
			color: #fff;
			font-size: 75%;
			border-radius: 2px;
		}
		/* 記事サムネイル画像 */
		.relPostWrap div.thumb img {
			height: 120px;
			width: 100%;
			object-fit: cover;
			vertical-align: bottom;
		}
		.relPostWrap div.thumb a:hover {
			opacity:0.75;
		}

	/* 記事タイトル */
	.relPostWrap div.title {
		margin-top: 6px;
		font-weight: bold;
	}
		/* 記事タイトル リンク */
		.relPostWrap div.title a {
			display: block;
			text-decoration: none;
			color: #1a1a1a;
		}

関連記事プラグイン

一応念のため、関連記事を表示できるプラグインへのリンクもいくつか貼っておきます。

Yet Another Related Posts Plugin (YARPP)
https://ja.wordpress.org/plugins/yet-another-related-posts-plugin/

WordPress Related Posts
https://ja.wordpress.org/plugins/wordpress-23-related-posts-plugin/

Contextual Related Posts
https://ja.wordpress.org/plugins/contextual-related-posts/

Similar Posts
https://ja.wordpress.org/plugins/similar-posts/

Related Posts by AddThis
https://wordpress.org/plugins/addthis-related-posts/

  • この記事を書いた人
  • 最新記事

hidepooh

日本では主にUNIXサーバーの構築、運用などに携わり、2006年に仕事を辞めてカナダに来てそのまま永住。 カナダでは、日本からカナダに留学や永住、ビジネスで渡航する人たちのサポートを行う傍ら、専門分野+趣味でもあるWeb制作、運用を継続しながら、最近では写真/動画撮影、動画制作、モーショングラフィックなど、新しい分野のスキルアップに励んでいます。 Peas Code は、僕が過去の経験の中で学んだことを、特定の分野に限定せず公開していくことを目的としています。中にはコードに見えてしまうような意味不明な僕独自の理論も含まれますが、知っていると平和になれると言う意味で、Peas(peace → peas) Code と名付けました。これが意味不明か・・・。 僕について、もうちょっと詳細を知りたいという変わった人は[About me]を見てください。

-WordPress
-,