I'm using the following query to fetch posts in a category (10). I would like to change this code to use the category slug or name instead of the id number as this often changes when I move sites about.??

<?php $custom_query = new WP_Query(array ('cat' => 10, 'showposts' => 1));
while($custom_query->have_posts()) : $custom_query->the_post();?>

I've tried changing ('cat' => 'books'... ('cat_name => 'books'... & also ('cat_slug => "books"... but nothing seems to work.

Many thanks

Following the first suggestion I've now got this working:

$query = new WP_Query('category_name=books');
while($query->have_posts()) : $query->the_post();?>

But now need help combining the "posts_per_page" bit of the query??


Lets start by removing the query_posts() from your code since you already have it's better brother new WP_Query.

Then what you will need is to use the category_name param on your WP_Query.

You should always search on the WP_Query page before you ask here, you can find more referencers there.

Here is how @speedypancake resolved the issue:

$the_query = new WP_Query(
        'posts_per_page' => '10', 
        'category_name' => 'books'
while( $the_query->have_posts() ): $the_query->the_post();
    // Do what you want
  • You mean like this?? <?php $custom_query = new WP_Query(array ('cat_name' => 'books', 'showposts' => 15)); while($custom_query->have_posts()) : $custom_query->the_post();?> Oct 26 '14 at 13:13

Following Bordoni's lead, and with a bit of trial and error, finally got it working

$the_query = new WP_Query( array ( 
'posts_per_page' => '10', 
'category_name' => 'books'
 ) );
while($the_query->have_posts()) : $the_query->the_post();

@Bordoni - Thanks for the hint!

  • don't forget to flag the answer as the correct one ;)
    – Bordoni
    Oct 26 '14 at 15:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.