I'm trying to query wordpress post by using query_posts and trying to save them in an array so that I get retrieve the post from array. This is what I'm doing,

    $posts =array();
    $args = array('posts_per_page' =>3,'cat' => 3 );
    $posts[] = query_posts( $args );

    global $post;
    if ( ! empty($posts) ) :
    foreach ($posts as $post) {
        echo get_the_title();

When I run this script it shows a post which is not in cat 3. but if I do print_r($post) it shows the correct three posts. Any idea of where I'm getting wrong?

2 Answers 2


try to use get_posts instead , as I read in http://codex.wordpress.org/Function_Reference/query_posts

you can use this code:

global $post;
$args = array('posts_per_page' =>3,'category' => 3 );
$myposts = get_posts( $args );

foreach( $myposts as $post ) :


  • I'm trying to put the posts into an array as you can see in my code I've used $posts = array() and $posts[] and that's because I'd run multiple queries and get posts out of them
    – user48752
    Mar 17, 2014 at 12:12
  • as you can see get_posts function return the posts array you want($myposts)
    – Ahmad Saad
    Mar 17, 2014 at 12:24
  • 2
    Use get_the_title( $post->ID ) instead. No need for setup_postdata either. Mar 17, 2014 at 12:30

query_posts() clobbers the global variable $wp_query. Don't use it:

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). Any modern WP code should use more reliable methods, like making use of pre_get_posts hook, for this purpose.


Note the very first line: "This function isn't meant to be used by plugins or themes."

Someone has already mentioned get_posts(), which is perfectly valid. However, I tend to prefer WP_Query for just about everything related to post retrieval, so I'd lean toward something like:

$args = array(
  'posts_per_page' => 3,
  'cat' => 1 
$cp = new WP_Query( $args );
foreach ($cp->posts as $p) {
  echo apply_filters('the_title',$p->post_title);

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.