Custom Query – exclude child category post from parent category post loop

I’m trying to change the way wordpress displays posts under category pages.

Ex:

Cat1 (contain 1 post)
Cat2 (contain 1 post)

Subcat2 (child of cat2 contain 1 post)

Cat3 (contain 1 post)

In the cat2 page, the loop will show the post of cat2 and the post of subcat2. I would like to hide this subcat2 post from the cat2 loop.

I’ve succeeded by editing archive.php with this code

<?php
if ( is_category() & !is_category(23) ) {
$cat = get_query_var(‘cat’);
query_posts(array(‘category__in’ => array($cat)));
}
?>

(23 is the ID of the top parent category, so, it’s normal it show all posts )

But this approach (editing archive.php) does not feet my needs (I’m using elementor template archives, so archive.php is ignored) and I would like to use the pre_get_posts hook in functions.php

So I’ve tried this:

add_action( ‘pre_get_posts’, function( $wp_query ){
if ( $wp_query->is_main_query() && $wp_query->is_category() & ! $wp_query->is_category(23) ) {
$cat = get_query_var(‘cat’);
$wp_query->set( ‘category__in’, [ $cat ] );
}
});

But the query doesn’t return anything… could you please tell me what is wrong in my code ?

Thx
Akal

Read more here:: Custom Query – exclude child category post from parent category post loop

Leave a Reply

Your email address will not be published. Required fields are marked *