0

My website has a group of main categories with their respective child categories. I am developing custom featured sections but needed help developing a WP_Query condition.

Is there a way to filter out posts filed to a 'Featured' category that also belong a certain category and it's children?

Example. My travel category (ID=1) has sub-categories like Hotels (ID=2), Tickets (ID=3), and Reviews (ID=4). I also have a Featured category (ID=8).

How do I filter posts filed to Featured but also belong to anyone of the above Travel category and/or sub-categories?

1 Answer 1

0

Follow the example code below, if you are using WordPress default post. For custom post type the query will be different.

<?php

$args = array(
    'category_name' => 'parent_category_slug+featured_category_slug', // change the category slug as your own
);

$query = new WP_Query($args);

if($query->have_posts()):

    while($query->have_posts()): $query->the_post(); ?>

    <h4><?php the_title(); ?></h4>

<?php
    endwhile; // main loop
    wp_reset_postdata();

endif; // have posts

?>
4
  • Would using the ID for the top category alone catch all posts filed in the sub-categories? For instance, if I checkmarked Hotels (sub category) but not the actual Travel category at the time of posting.
    – BW00
    Feb 14, 2018 at 10:19
  • Yes. It does. Please check it, it should work for what are you looking for. Feb 14, 2018 at 16:54
  • I tried it and it does not work as expected. It only pulls from either or, and does not filter as I wanted it to.
    – BW00
    Feb 14, 2018 at 22:53
  • Sorry, I was missed your point. I edited the code, try it. It will pull posts from which is belongs to featured category and also the parent category or it's child category Feb 15, 2018 at 3:52

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.