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

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


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!


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