How to Show Only Same-Category Posts in "Recent Posts" on WordPress

English

Continuing from my last post, I've been exploring how to prevent the "Recent Posts" widget from displaying unrelated content that readers aren't interested in. There was nothing useful when I googled it, so I decided to analyze it myself. If successful, I'll put the conclusion right at the beginning. This is for the Lightning theme.

Conclusion: Modify the Lightning Theme's PHP Code in sidebar-contents-post.php

First, for those who don't care about the process, here is the brief conclusion.
Here is how to make the "Recent Posts" section in the sidebar of a single post page in Lightning display only items from the same category as that post. By the way, this also restricts the sidebar on category archive pages to that same category.

The file is located at:
/var/www/html/wp-content/themes/lightning/_g3/template-parts/sidebar-contents-post.php

Modifying the Code to Filter by the Same Category as the Current Article

/same categoryのため新規変数を追加する
$cats   = get_the_category(); //categoryは配列で入る
$cat_id = $cats[0]->term_id;  //一つ目のcategory ID

//test
//echo $cat_id; echo ':';echo($cats[0]->name);echo '</p>';
//var_dump($cats[0]);echo '</p>';
//var_dump(get_the_category()[0]);echo '</p>';//続けてかいてもよし

$post_loop = new WP_Query(
	array(
		'post_type'              => 'post',
	        'cat'                    => $cat_id,//add for restruct same category
		'posts_per_page'         => 10,
		'no_found_rows'          => true,
		'update_post_meta_cache' => false,
		'update_post_term_cache' => false,
	)
);
?>

You will need to add the code where I've highlighted the pink fluorescent line.

Later on, I also explain how to rewrite "Recent Posts" to "Recent Posts in [Category Name]", so make sure to read until the end.

First Steps: Exploring around lightning/_g3 based on insights from the previous article.

This file looks suspicious:
/var/www/html/wp-content/themes/lightning/_g3/template-parts/sidebar-contents-post.php
The filename suggests it handles "sidebar content for posts".
This is our entry point.

 * 投稿タイプ post 用のサイドバーです。
 * しかし、サイトバーウィジェットエリア(投稿)にウィジェットかブロックが配置されている場合、
 * このファイルは読み込まれなくなります。

There is a comment like the above at the beginning. Initially, I wondered if I could handle this through the Lightning browser settings and stumbled upon the sidebar widget settings. However, I couldn't figure out how to use it at all. It seems that if you specify certain options, this processing gets disabled.

$post_loop = new WP_Query(
	array(
		'post_type'              => 'post',
		'posts_per_page'         => 10,
		'no_found_rows'          => true,
		'update_post_meta_cache' => false,
		'update_post_term_cache' => false,
	)
);
?>

This part handles the settings. Since it's passed as an argument to the while loop, it must be the loop condition. If it displays 10 posts and you want fewer, you apparently change the number here. I tried changing this number to 5 and reloaded the article, and the change was applied immediately. There's no doubt this is the right entrance.

Next up is...

<?php if ( $post_loop->have_posts() ) : ?>
<aside class="widget widget_media">
<h4 class="sub-section-title"><?php echo __( 'Recent posts', 'lightning' ); ?></h4>
<div class="vk_posts">
	<?php
	while ( $post_loop->have_posts() ) :
		$post_loop->the_post();

		$options = array(
			'layout'                     => 'media', // card , card-horizontal , media
			'display_image'              => true,
			'display_image_overlay_term' => true,
                   〜略〜
		);
		wp_kses_post( VK_Component_Posts::the_view( $post, $options ) );

endwhile;
	?>

It looks like a function definition. Looking inside, it feels like it loops for as many posts as there are. Since it says `php echo __( 'Recent posts'`, this must be it. How does localization work, anyway? It seems to rely on an English-Japanese lookup table in `lightning-ja.po`.
It probably loops through the available posts and displays them using `wp_kses_post( VK_Component_Posts::the_view( $post, $options ) );`.
Should we insert a conditional check around here to see if it matches the current article? Unlike the previous article, it doesn't seem as simple as just toggling a standard function on or off.

The Key is WP_Query()

Looking up WP_Query, it has all sorts of features, and you can specify various conditions specifically for post loops.
https://wpdocs.osdn.jp/%E9%96%A2%E6%95%B0%E3%83%AC%E3%83%95%E3%82%A1%E3%83%AC%E3%83%B3%E3%82%B9/WP_Query
Vibe-wise, it would be great if we could just specify the "category" in the parameter settings we saw earlier.

The "Category Parameters" section on this site looks like a good hint.

あるカテゴリーに関連付けられた投稿を[show]する。
cat (整数) - カテゴリー ID を使用します。
category_name (文字列) - カテゴリーのスラッグ(カテゴリ名ではありません)を使用します。
category__and (配列) - カテゴリー ID を使用します。
category__in (配列) - カテゴリー ID を使用します。
category__not_in (配列) - カテゴリー ID を使用します。

https://wpdocs.osdn.jp/%E9%96%A2%E6%95%B0%E3%83%AA%E3%83%95%E3%82%A1%E3%83%AC%E3%83%B3%E3%82%B9/WP_Query

I see, I see. If we are setting category parameters statically, using category slugs seems like an easy way to limit them.

You can also specify multiple categories by listing them separated by commas.
$query = new WP_Query( 'category_name=fishing,camp' );

Nice. Our goal this time is to match the category of the currently displayed article. All we need to do is fetch the category ID of the current article and pass it through.

Fetching the Category ID of the Current Article

I Googled it. Thank you, internet.
https://www.nowte.net/wordpress/wordpress-get-category-data/

現在[show]している記事の1番目のカテゴリースラッグを[show]

<?php
$cat = get_the_category();
$cat = $cat[0];
echo $cat->slug; ?>

https://www.nowte.net/wordpress/wordpress-get-category-data/

Since I only allow a single category to be assigned, I should be good with this approach, right?
*Wait, the variable changes from `cat` [array] to `cat` (not an array) midway through. That's kind of annoying.

現在[show]している記事のカテゴリーを複数[show]

<?php
$cats = get_the_category();
foreach($cats as $cat){
echo $cat->cat_name;
echo $cat->slug; }
?>

https://www.nowte.net/wordpress/wordpress-get-category-data/

It seems possible to fetch multiple categories too. Since the setting side could also take multiple values, would that be safer? But it looks like it might get complicated.

The Code to Modify

/var/www/html/wp-content/themes/lightning/_g3/template-parts/sidebar-contents-post.php
This is the file that appeared earlier. Thanks to my previous WordPress knowledge, I got here pretty quickly this time. Everything was a bullseye. However, I struggled a bit with writing the PHP code.

Modification 1: Filtering by the Same Category as the Current Article

/same categoryのため新規変数を追加する
$cats   = get_the_category(); //categoryは配列で入る
$cat_id = $cats[0]->term_id;  //一つ目のcategory ID  例)2:web構築日記

//test
//echo $cat_id; echo ':';echo($cats[0]->name);echo '</p>';
//var_dump($cats[0]);echo '</p>';
//var_dump(get_the_category()[0]);echo '</p>';//続けてかいてもよし

$post_loop = new WP_Query(
	array(
		'post_type'              => 'post',
	        'cat'                    => $cat_id,//add for restruct same category  0 is all
		'posts_per_page'         => 10,
		'no_found_rows'          => true,
		'update_post_meta_cache' => false,
		'update_post_term_cache' => false,
	)
);
?>

I'll add the code where the pink fluorescent line is highlighted.
The yellow fluorescent line is diagnostic code for research purposes. For reference, it will output to the browser.


I'm not used to prefixing variables with `$` in PHP, so I stumbled for a moment by forgetting the `$` in `$cat_id=cats[0]->term_id`, writing it as `cats` instead. By the way, is there a reason why object properties don't take a `$`?

Modification 2: Changing "Recent Posts" to "Recent Posts in [Category Name]"

I want to change the display of "Recent Posts" to "Recent Posts in [Category Name]".

<h4 class="sub-section-title"><?php echo __( 'Recent posts', 'lightning' ); ?></h4>

Just below Modification 1, right before the loop processing, there is a line similar to the above. This is where "Recent posts" is outputted to HTML. It probably goes through some magic to become the Japanese "最近の投稿", but that's a hassle to figure out, so I'm going to bypass the mechanism and output it directly.
What I want to do is prepend the static text "Category:" + [Category Name] + "Recent Posts" before the heading.

<h4 class="sub-section-title">
    「
    <?php echo($cats[0]->name); /*この辺追加*/ ?>
    」のカテゴリーの
    <?php echo __( 'Recent posts', 'lightning' ); ?>
</h4>

It's hard to read on a single line, so I'll break it up and append it. The text stays as it is, and for [Category Name], we write the code between `<?php` and `?>` using PHP as we learned earlier. Outputting text is done with `echo`. And we can reuse the category information variable `cats[]` from earlier. The property name for the category name is `'name'`, and there are various other variables too, so feel free to play around with them.

And with that, we're done.

Result: It Worked!

A single page of recent posts.

By the way, category top pages started doing this too. They must be sharing the same template.

On my site, interests are neatly grouped under parent category pages, so it might actually be nice to display posts from the parent category instead. Since the post's category info also contained the parent ID, could I just collect that and all its child IDs into an ID-only array and pass it? Until next time!

Leave a Reply