开发者

can I run new WP_Query inside the Loop with no affects to the Loop? (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>';
}


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.


Are you missing some php opening and closing tags when enclosing the new query in the function? This works as a standalone new query loop that can be used multiple times inside the main WP loop:

<?php $my_query = new WP_Query('author_name=Radek&showposts=2'); ?>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
<?php the_title(); ?></a>
<?php endwhile; ?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜