LoginSignup
1
2

More than 3 years have passed since last update.

Wordpressでプラグインを使わずに関連記事を表示する方法 2020年版

Posted at

関連記事は、関連度やタグもカテゴリも含むなど高度な設定が必要な場合はプラグインを使ったほうが早いかも。

ここでは簡単な関連記事の取得方法をまとめる。

プラグイン使わず関連記事を実装

functions.phpに以下のコードを追記。

// functions.php
function my_get_related_posts( $post_id, $related_count ) {
  // 記事のカテゴリを取得、タグでも可
  $terms = get_the_terms( $post_id, 'category' );

  if ( empty( $terms ) ) $terms = array();

  // カテゴリ一覧のslugを作成
  $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',  // ランダム、DESCで新着順に変更可能
    'tax_query' => array(
      array(
        'taxonomy' => 'category', // カテゴリから取得
        'field' => 'slug',  // $term_listでslugとってるので合わせる
        'terms' => $term_list // カテゴリ一覧のslugを渡す
      )
    )
  );
  return new WP_Query( $related_args );
}

テンプレートに関連記事

あとはテンプレートの表示したい位置にループ処理を書き込むだけ。

<h1>関連記事</h1>
<ul>
<?php
global $post;
$wp_query = my_get_related_posts( $post->ID, 6 );
if ($wp_query->have_posts()) : while ($wp_query->have_posts()) : 
  $wp_query->the_post(); ?>

    <li>
      <a href="<?php echo get_permalink(); ?>">
        <img src="<?php echo get_the_post_thumbnail_url(); ?>" alt="<?php echo get_the_title(); ?>">
        <p><?php echo get_the_title(); ?></p>
      </a>
    </li>

<?php endwhile; endif; wp_reset_postdata(); ?>
</ul>
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2