12% off of LTD using this coupon: TWELVEPERCENTOFF. Promo ends on 2 Dec midnight UTC.
Published on Nov 17, 2022

Limit posts to only those directly in the current category

Sridhar Katakam

In the WPDevDesign Facebook group a user asks:

I have categories on the site that has sub categories. On the parent category page, I do not wish to show the posts of all the sub categories, just the posts that are directly in the parent category but on the child category pages, show the posts assigned to that child. Is it possible to filter the repeater for this?

When a category archive is being viewed on the frontend, WordPress will not only show the posts that are directly assigned to the current category being viewed but also any posts that may be in child categories of the current category.

We can use the amazing pre_get_posts filter to pre-filter the posts to only those that are directly in the current category.

Add the following code in a code snippets plugin:

<?php 

add_action ( 'pre_get_posts', function( $query ) {
	if ( $query->is_main_query() && ! is_admin() && $query->is_category() ) { 
		$query->set( 'category__in', get_queried_object_id() );
	}
});

Reference: https://wordpress.stackexchange.com/a/372174/14380

tagschevron-leftchevron-rightchainangle-rightangle-upangle-downfolder-omagnifiercrossmenuchevron-downarrow-right