WordPress: How to filter posts by category using $wp_query?

42,437

Solution 1

You have to use category_name (string - use category slug) or cat (int - use category id), to get post by category in WP_Query::query().

Here is an example:

$category_name = 'apples'; //replace it with your category slug
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query();
$wp_query->query('showposts=1' . '&paged=' . $paged . '&category_name=' . $category_name);
//...
//...

Hope this helps!

Solution 2

Delete your first php block and replace it with this

<?php
$args = array (
    'showposts' => '1',
    'category_name' => 'apples',
    'paged' => $paged
);
$the_query = new WP_Query( $args );

if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post();
?>

For more information https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters

Share:
42,437
kidcoder
Author by

kidcoder

When you downvote me, you're really downvoting yourself.

Updated on July 11, 2021

Comments

  • kidcoder
    kidcoder almost 3 years

    I built a custom theme on WordPress with a static front page and no page set in Settings > Reading Settings > Front page displays as a posts page. I'd like to display posts, however, based on their categories throughout the site on different static pages. Therefore, I will never declare a posts index page through the console. And so I use the $wp_query function.

    How can I add a filter to this script that only displays posts in the category "apples" (for example)? Right now, this script shows all posts regardless of category.

    <?php
        $temp = $wp_query;
        $wp_query = null;
        $wp_query = new WP_Query();
        $wp_query->query('showposts=1' . '&paged='.$paged);
        while ($wp_query->have_posts()) : $wp_query->the_post();
    ?>
    
    <h2><a href="<?php the_permalink(); ?>" title="Read"><?php the_title(); ?></a></h2>
    <?php the_excerpt(); ?>
    <?php the_date(); ?>
    
    <?php endwhile; ?>
    
    <?php if ($paged > 1) { ?>
        <p><?php previous_posts_link('Previous page'); ?>
        <?php next_posts_link('Next page'); ?></p>
    <?php } else { ?>
        <p><?php next_posts_link('Next page'); ?></p>
    <?php } ?>
    
    <?php wp_reset_postdata(); ?>