WP Simple Related Posts
- カテゴリやタグをベースとした関連記事を出すプラグイン。
- 投稿編集時に任意の記事に置き換えることもできる。
- 自動で本文の最後に表示される(表示項目は記事のタイトルとリンク)
かつアイキャッチ画像や抜粋をよしなに表示したい場合のカスタマイズ
関連記事のID取得
GitHubに説明ある通り。パラメーターはよしなに。
<?php
$ids = sirp_get_related_posts_id();
戻り値が連想配列なので注意
array(3) {
    [0]=> array(1) {
        ["ID"]=> string(4) "7763"
    }
    [1]=> array(1) {
        ["ID"]=> string(4) "7757"
    }
    [2]=> array(1) {
        ["ID"]=> string(4) "7753"
    }
}
アイキャッチ画像や抜粋の表示
アイキャッチ画像は投稿IDを渡して取得できるが、抜粋( the_excerpt(), get_the_excerpt() )はループ外で使えない=投稿IDを渡してもグローバル変数の $post を参考にしてしまうので、関連記事のIDで forearch するのではなく、WP Queryクラス(または get_posts() ) で処理しましょう。
htmlタグとかはよしなに変更してください。
my_simple_related_posts.php
<?php
function my_simple_related_posts() {
	// プラグインが有効化されてなかったら関数がないってことなので終了
	if ( ! function_exists( 'sirp_get_related_posts_id' ) )
		return;
	$related_posts_ids = sirp_get_related_posts_id();
	// 関連記事IDがなかったら終了
	if ( empty ( $related_posts_ids ) )
		return;
	// WP_Query クラスに渡す為にsirp_get_related_posts_id()の戻り値をよしなに変更
	$ids = array();
	foreach ( $related_posts_ids as $related_posts_id ) {
		$ids[] = $related_posts_id['ID'];
	}
	if ( empty ( $ids ) )
		return;
	// 配列を整形した投稿IDを元に投稿を取得
	$related_posts = new WP_Query( array(
		'posts_per_page' => -1,
		'post__in'       => $ids,
		'order'          => 'ASC',
		'orderby'        => 'post__in'
	) );
	if ( $related_posts->have_posts() ) {
		echo '<h3>関連記事</h3>';
		echo '<ul>';
		// ループ開始
		while ( $related_posts->have_posts() ) {
			$related_posts->the_post();
			echo '<li>';
			echo '<a href="' . get_the_permalink() . '">';
			if ( has_post_thumbnail() ) {
				the_post_thumbnail( 'thumbnail' );
			}
			the_title( '<h4>', '</h4>' );
			echo '<div class="excerpt">';
			the_excerpt();
			echo '</div>';
			echo '</li>';
		} // ループ終わり
		echo '</ul>';
	}
	wp_reset_postdata();
}
現場からは以上です。
