WP Snipp Ninja

Create a query from a single category slug

Author: Dimitar Radev | Posted on: September 11, 2018 |

The function below creates a WP_Query object and takes two variables. $cat – category slug and $per_page – how much posts should be displayed per page.

 /* Create WP_Query from category slug and output it to a variable
 * @param  string $cat      category slug
 * @param  int    $per_page posts per page
 * @return obj    returns WP_Query object

function do_cat_query( $cat, $per_page )
  $cat_obj = get_category_by_slug( $cat );
  $cat_id = $cat_obj->term_id;
  $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

  // WP_Query arguments
  $args = array(
    'post_type'              => 'post',
    'cat'                    => $cat_id,
    'posts_per_page'         => $per_page,
    'paged'                  => $paged,
    'order'                  => 'DESC',
    'orderby'                => 'date'

  // The Query
  $query = new WP_Query( $args );

  return $query;

To use it simply to rewrite the $wp_query in that template as shown below.

$wp_query = do_cat_query('stories', 5);

This will give you the option to use all features just as a normal page however if you need to save the initial query data for later use, assign it to a different variable before overwriting $wp_query.

Like so:

$page_query = $wp_query;
$wp_query = do_cat_query('stories', 5);

Now you can use the initial query as shown below:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

About the Author

 Dimitar Radev

Hey, I'm Dimitar "B1-0S" Radev or D in short. I'm a WordPress Developer for nearly 10 years and I have in-depth knowledge in creating Custom WordPress Themes, Plugins, Commercial Themes Edits, and WooCommerce Storefronts. In the last two years, I'm specializing in Technical SEO for WordPress websites.

Follow Dimitar Radev on Social Media

Leave a Reply

Your email address will not be published. Required fields are marked *