Reputation: 303
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) {
setup_postdata($post);
echo get_the_title();
}
wp_reset_postdata();
endif;
wp_reset_query();
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?
Upvotes: 1
Views: 108
Reputation: 4124
This one should work also WP_Query or get_posts() is preferred method for secondary queries.
global $post;
$posts_args = array('cat' => 3, 'posts_per_page' => 3);
$posts_query = new WP_Query($posts_args);
$posts_arr = $posts_query->get_posts();
if ( ! empty($posts_arr) ) :
foreach ($posts_arr as $post) {
setup_postdata($post);
echo get_the_title();
}
wp_reset_postdata();
endif;
wp_reset_query();
Upvotes: 1
Reputation: 48711
No need to declare it as an array:
global $post;
$args = array('posts_per_page' => 3,'cat' => 3);
$query = query_posts($args);
foreach ($query as $post) {
setup_postdata($post);
the_title();
}
wp_reset_query();
Upvotes: 1
Reputation: 3348
Remember that query_posts modifies the main loop, so probably the post that is not from cat = 3 is from the main loop. Try to create a new query with get_posts.
$posts = get_posts('posts_per_page=3&cat=3');
global $post;
if (!empty($posts)):
foreach ($posts as $post):
setup_postdata($post);
echo get_the_title();
endforeach;
wp_reset_postdata();
endif;
Upvotes: 0