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(); ?>
If you want to recieve the latest WordPress snippets, tutorials, tricks and useful information about web development, seo, social media marketing, google you can Subscribe to our newsletter. All you need to do is to fill the Subscribe form below, verify your Free Subscription in your email and start read our daily useful tips and tricks straight in your mailbox.
Note* we hate spam and our newsletter is powered by Google Feedburner and you will not get spam messages in your mailbox.
Leave a Reply