Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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(); ?>
like image 816
kidcoder SAVE UKRAINE Avatar asked Jan 27 '17 03:01

kidcoder SAVE UKRAINE


2 Answers

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!

like image 192
Raunak Gupta Avatar answered Sep 28 '22 08:09

Raunak Gupta


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

like image 40
Ed Dogan Avatar answered Sep 28 '22 06:09

Ed Dogan