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

acidgate picture acidgate · Jan 27, 2017 · Viewed 28.8k times · Source

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(); ?>

Answer

Raunak Gupta picture Raunak Gupta · Jan 27, 2017

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!