Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can I run new WP_Query inside the Loop with no affects to the Loop? (wordpress)

Tags:

wordpress

the bellow function is working fine but I need to run it inside the loop. If done so the post content is actually taken from the last post of my WP_Query. Not from the one that should appear.

Is there any way to run my query and leave The Loop unaffected?

function recent_post_by_author() {
  echo '<div class="recent_post_by_author">';
  $my_query = new WP_Query('author_name=Radek&showposts=2');
  while ($my_query->have_posts()) : $my_query->the_post(); ?>
  <a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"> <?php the_title(); ?></a><BR>
  <?php endwhile;
  echo '</div>';
}
like image 413
Radek Avatar asked May 16 '10 05:05

Radek


People also ask

How do I use a while loop in WordPress?

The Loop is PHP code used by WordPress to display posts. Using The Loop, WordPress processes each post to be displayed on the current page, and formats it according to how it matches specified criteria within The Loop tags. Any HTML or PHP code in the Loop will be processed on each post.

What is the use of WP_Query in WordPress?

WP_Query is a class defined in WordPress. It allows developers to write custom queries and display posts using different parameters. It is possible for developers to directly query WordPress database. However, WP_Query is one of the recommended ways to query posts from WordPress database.

What is Wp_reset_postdata ()?

wp_reset_postdata() restores the global $post variable to the current post in the main query (contained in the global $wp_query variable as opposed to the $sec_query variable), so that the template tags refer to the main query loop by default again.

What is query loop WordPress?

The Query Loop Block is an advanced block that allows you to display posts based on specified parameters; like a PHP loop without the code. In WordPress, The Loop means to display specific data in a repeated manner. Each post generally shows a title, author, date, post content, and comments.


1 Answers

The fix for this is to call wp_reset_postdata after you're done looping through your separate WP_Query instance.

The problem is showing up because WordPress uses a global $post variable that is set whenever a call to the_post() is made on any WP_Query object. When you call it from your 2-posts-from-Radek query, it loses track of the original WP_Query object.

like image 68
Nate Cook Avatar answered Sep 23 '22 11:09

Nate Cook