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>
希望通りの表示ができました。
ついでにsingle.phpを改造して、ブログの「投稿」(個別記事やニュース)を表示する時に、その投稿の関連カテゴリの投稿一覧を表示するようにしました。
<?php
$post_id = get_the_ID(); // 投稿のIDを取得
$categories = get_the_category($post_id); // 投稿のカテゴリーを取得
$cat_ids = []; // カテゴリーIDを格納するための空の配列を用意
foreach ($categories as $category) :
array_push($cat_ids, $category->term_id); // 用意した空配列にカテゴリーIDを格納
endforeach;
$args = [
‘post_type’ => ‘post’, // 投稿タイプを指定
‘posts_per_page’ => ’30’, // 表示する記事数を指定
‘category__in’ => $cat_ids, // カテゴリーIDを指定
‘post__not_in’ => [$post_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>
<?php
endif;
wp_reset_postdata(); ?>
</div>


















