You can Query a lot of time in the same page and all the query that you execute will work perfect irrespective of the custom post type that you choose.
Note: Once after you finish the Wp_Query at the first time you need to
reset
theWp_Query
after the execution of the code.
wp_reset_query(); // This will reset all the global variables to "".
wp_reset_query()
restores the $wp_query and global post data to the original main query. This function should be called after query_posts(), if you must use that function. As noted in the examples below, it’s heavily encouraged to use the pre_get_posts filter to alter query parameters before the query is made.
Not only by this method you can reset the Wp_Query
there are other methods that you can follow up for resetting the post data
and as well as the $args
.
Quick Reference About the Resetting Query options.
wp_reset_query()
– best used after a query_posts loop to reset a custom querywp_reset_postdata()
– best used after custom or multiple loops created with WP_Queryrewind_posts()
– best for re-using the same query on the same page.
I hope this is a useful round-up of when & how to reset/rewind the WordPress loop
wp_reset_postdata()
$random_post = new WP_query();
$random_post->query('cat=3&showposts=1&orderby=rand');
while ($random_post->have_posts()) : $random_post->the_post();
<a href="https://wordpress.stackexchange.com/questions/240744/<?php the_permalink() ?>" title="<?php the_title(); ?>">
<img src="<?php echo get_post_meta($random_post->ID, 'featured', true); ?>">
</a>
endwhile;
wp_reset_postdata();
When to use: best used after custom or multiple loops created with WP_Query.
wp_reset_query()
<?php query_posts('posts_per_page=3');
if (have_posts()) : while (have_posts()) : the_post(); ?>
<h1><a href="https://wordpress.stackexchange.com/questions/240744/<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
<?php endwhile; endif; ?>
<?php wp_reset_query(); ?>
When to use: best used after a query_posts loop to reset things after a custom query.
rewind_posts()
if (have_posts()) : while (have_posts()) : the_post(); ?>
<h1><a href="https://wordpress.stackexchange.com/questions/240744/<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
<?php endwhile; endif; ?>
<?php rewind_posts(); ?>
<?php while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
So, while wp_reset_query
and wp_reset_postdata
reset the entire query object, rewind_posts simply resets the post count, as seen for the function in the wp-includes/query.php
file:
// rewind the posts and reset post index
function rewind_posts() {
$this->current_post = -1;
if ( $this->post_count > 0 ) {
$this->post = $this->posts[0];
}
}
When to use: best for re-using the same query on the same page.