ワードプレスで現在表示中の記事の関連記事を表示するために、同一カテゴリーから現記事を除外して投稿を複数取得する簡単なプログラムをご紹介します。

下記PHPコードは作成されているプラグインやテーマのFunctions.php等で動作します。
function cats_related_post($post_id) {
$returnarray = array();
$cat_ids = array();
$categories = get_the_category( $post_id );
if(!empty($categories) && !is_wp_error($categories)):
foreach ($categories as $category):
array_push($cat_ids, $category->term_id);
endforeach;
endif;
$query_args = array(
'category__in' => $cat_ids,
'post_type' => 'post',
'orderby' => 'date',
'order' => 'DESC',
'post__not_in' => array($post_id),
'posts_per_page' => '10',
);
$related_cats_post = new WP_Query( $query_args );
if($related_cats_post->have_posts()){
while($related_cats_post->have_posts()): $related_cats_post->the_post();
$returnarray[]=get_the_ID();
endwhile;
wp_reset_postdata();
}
return $returnarray;
}
上記関数に、現在表示中の記事の投稿のIDを渡して呼び出すと、同一カテゴリーの属する関連記事のIDを最大10個配列で返します。
・get_the_category( $post_id ) でこの記事のカテゴリーリストを取得し、‘category__in’ => $cat_ids,にてこの記事と同じカテゴリーの属する投稿の記事を WP_Query 関数で取得します。
・関連記事を取得したいので ‘post__not_in’ => array($post_id),にて自身の投稿は除外します。
・‘posts_per_page’ => ’10’, 最大10件の記事取得はここで設定されています
・while($related_cats_post->have_posts()): $related_cats_post->the_post(); の下3行で配列に関連記事のIDをすべていれて返します




