0

I'm currently using a filter applied to the Archive Widget. It's successfully filtering posts from the specific category (26) but now I also want to filter only PARENT posts, in order to count only PARENT posts from this category.

I'm currently using the following, but not working:

function my_nav_archives($args){
    $args['cat'] = 26;
    $args['post_parent'] = 0;

    return $args;
}
add_filter( 'widget_archives_args', 'my_nav_archives' );

Is there any other argument I can use? Thanks.

3
  • I'm not sure if you understand the definition of a Parent Post as it is used in the Wordpress structure. Pages (a type of post within WP) can have a hierarchical with PARENTS. Posts, by default, cannot. It would require a special plugin to add that hierarchy. Without that special structure, $args['post_parent']=0 should return all posts in $args['cat']=26. Have you added a plugin to establish hierarchical Posts? Commented Sep 13, 2019 at 18:42
  • 1
    Sorry I've not made that clear... Yes, I've added an ACTION to my functions.php that enables hierarchy in posts, using the code on the accepted answer here:stackoverflow.com/questions/10750931/…
    – Luis
    Commented Sep 17, 2019 at 10:21
  • Looking more closely at Wordpress Core , I'm actually surprised that your cat argument works. It appears the available arguments are totally different from WP_Query args. Take a look at function widget($args,$instance) beginning on line 42, and compare it to the codex. It would appear you just got lucky with $args['cat']. Hope somebody can prove me wrong and find a solution for you... Commented Sep 25, 2019 at 17:21

1 Answer 1

0

I haven't tested this, but I found a sample that was close. I have modified it to be similar to what you want. I'm not sure it is 100%, but it should get you really close:

add_action('pre_get_posts','wpse_filter_parents_only');

function wpse_filter_parents_only($query){
    if (!is_admin() && is_category('26')){
        $query->set('post_parent',0);
    }
    return $query;
}

This should update what WP_Query retrieves from the database, and only for category 26. If you need this to affect multiple categories, stuff them into an array and insert the array like this: is_category($cats).

Hope this helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.