カテゴリ別のページで同じカテゴリの投稿一覧を表示

WordPressで昔のままのプラグインを使っていたら、PHPのアップデートができなくなりました。
PHPのアップデートをするとエラー表示になるのです。
それで現在使っているプラグインで新しいバージョンのPHPに対応していないものを削除しました。
その中にMy Category Orderが、あったのですが、My Category Orderを削除したら、カテゴリのページに入っても、そのカテゴリのページ一覧が見れないので都合が悪いです。

https://web-dev.tech/wordpress/customize/display-related-posts-from-the-same-categories/
を参考にして、使っているthemes(wp-content\themes\*******のcategory.php)を書き換えて下記を挿入しました。
挿入する位置は

<div id=”container”>
<div id=”content” role=”main”>
<h1 class=”page-title”><?php
printf( __( ‘Category Archives: %s’, ‘twentyten’ ), ‘<span>’ . single_cat_title( ”, false ) . ‘</span>’ );
?></h1>
の下です

<?php
$cat_id = get_queried_object()->term_id; // カテゴリーを取得

$args = [
‘post_type’ => ‘post’, // 投稿タイプを指定
‘posts_per_page’ => ‘100’, // 表示する記事数を指定
‘category__in’ => $cat_id, // カテゴリーIDを指定
];

$related_cats_query = new WP_Query($args);
?>

<div class=”related-posts”>
<?php if ($related_cats_query->have_posts()) : ?>
<ul>
<?php while ($related_cats_query->have_posts()) : $related_cats_query->the_post(); ?>
<li>
<a href=”<?php the_permalink(); ?>”>
<?php the_title(); ?>
</a>
</li>
<?php endwhile; ?>
</ul>
<?php else : ?>
<p>関連記事はありません。</p>
<?p
endif;
wp_reset_postdata(); ?>
</div>

希望通りの表示ができました。

コメントを残す

メールアドレスが公開されることはありません。 ※ が付いている欄は必須項目です