Friday, June 8, 2018

Wordpress: How to query posts using category filters

Show all posts that belong to category ID "50"

In your loop template, please use the following format (see comments for details):
    <?php $query = new WP_Query( array( 'cat' => '50' ) ); //50 is the category id, you can see it in the url when editing the category ?>
    <?php if ( $query->have_posts() ) : //get the filtered posts ?>
    <?php while ( $query->have_posts() ) : $query->the_post(); ?>
            <div class="post-content">
                <?php echo the_post_thumbnail(); ?>
                <?php echo the_title( '<h2><a href="#">', '</a></h2>' ); ?>
    <?php endwhile; ?>
    <?php wp_reset_query(); ?>
    <?php endif; ?>

Show all posts that do not belong to category ID "50":

    <?php $query = new WP_Query( array( 'cat' => '-50' ) ); //the minus sign means "exclude" ?>
    <?php if ( $query->have_posts() ) : //get the filtered posts ?>
    <?php while ( $query->have_posts() ) : $query->the_post(); ?>
            <div class="post-content">
                <?php echo the_post_thumbnail(); ?>
                <?php echo the_title( '<h2><a href="#">', '</a></h2>' ); ?>
    <?php endwhile; ?>
    <?php wp_reset_query(); ?>
    <?php endif; ?>
For additional query filters, please see: https://codex.wordpress.org/Class_Reference/WP_Query

No comments:

Post a Comment