2

I am trying to query multiple category in wordpress but no luck, I don’t see anything wrong with my code.

Herewith my code below :

query_posts('posts_per_page=1&cat=5,1');

  while ($wp_query->have_posts()) : $wp_query->the_post(); 

  get_template_part('loop', 'single-home');

endwhile;
1
  • The problem with this question is that you don't clarify whether you want posts in either category or that they have to be in both categories. Commented Jul 5, 2023 at 19:28

2 Answers 2

5

Use like this

query_posts( array( 'category__in' => array(5,1), 'posts_per_page' => 1, 'orderby' => 'title', 'order' => 'ASC' ) );

or

$my_query = new WP_query(array('category__and' => array(5,1))); 
while ($my_query->have_posts()) : $my_query->the_post(); 
2
  • it alright the first one it working
    – Jono
    Commented Oct 6, 2014 at 10:10
  • if my answer helps you then please accept it as the answer by clicking the tick symbol
    – Zammuuz
    Commented Oct 6, 2014 at 10:13
2

First of all, never use query_posts

Note: This function isn't meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query. query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination).

You should rather use WP_Query to create custom queries

Secondly, your problem is your posts_per_page parameter. That is set to 1. What this means is that one post will be retrieved which will come from either cat 1 or cat 5, depending which post is the newest between the two cats. You have to increase 1 to retrieve more posts, set 1 to -1 to retrieve all posts from these two categories.

You can also remove the posts_per_page parameter and replace it with nopaging=true to retrieve all posts.

1
  • This should be the accepted answer, IMO. Avoid using query_posts.
    – Olivier
    Commented Jan 13, 2023 at 15:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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