Support » Developing with WordPress » Filtering ‘Featured’ posts in a category page

  • I am trying to create customized category pages. At the top of each page, I’d like to have two posts which basically are featured posts. Currently on the home page, I have a condition where posts from the ‘Featured’ category show up. However I am trying to create a conditional statement that factors in both when viewing category pages.

    So for instance, I have Travel section which has a few child categories as well. I’d like to now pull posts from the Travel category and respective child categories, which are also filed under Featured.

    This is a sample of my code I use for the index at the moment.

    <?php $my_query1 = new WP_Query('showposts=2&category_name=featured'); ?>
    <?php while ($my_query1->have_posts()) : $my_query1->the_post(); ?>
    [post styling here]
    <?php endwhile;?>

    Is it possible to start off with something like category_name=travel+hotels+reviews and then have some kind of sub-query to filter out the posts from those categories that also are filed under “Featured”?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Hi,

    If you need to display the pasts from different categories, then you can use query by category:
    $query = new WP_Query( array( 'cat' => '2,6,17,38' ) );
    $query = new WP_Query( array( 'category__in' => array( 2, 6 ) ) );

    It depends on whether the post will have only 1 category travel + hotels + reviews and Featured or the post should have both categories.

    @bestwebsoft Doesn’t really answer my question specifically. I already know how to filter by, but then where does the sub routine fit in to pull posts filed to the Featured category which also belongs to those?

    Moderator bcworkz


    There isn’t a possibility of a sub-routine like you imagine within the WP_Query class. You can simulate such behavior external to the class, but before we look at what that might entail, let’s try doing it all in one query. Setup a new WP_Query like in bestwebsoft’s second example using ‘category__in’. Determine the term ID for your featured class and use it in a similar ‘category__not_in’ argument added to the overall arguments array passed when instantiating WP_Query. If the ID for featured is 8 for example, then something like

    $query = new WP_Query( array( 
       'category__in' => array( 2, 6 ),
       'category__not_in' => array( 8 ),
     ) );
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Filtering ‘Featured’ posts in a category page’ is closed to new replies.