Hi I am setting up a random post generator so that a list of random posts from a chosen category can be displayed on a post. I also made it into a shortcode so it could be applied in an editor. THE ISSUE is that, it is displaying comments from the random posts generated. And I can't figure out why.

I do think it is something to do with the while loop I am using for this function, and it is for some reason interacting with the loop in the single.php and 'comments_template()' function, but I am not sure how to stop it

here is my code:

function aa_related_posts($id){

$args = array(
    'cat' => $id,
    'orderby' => 'rand',
    'posts_per_page' => '4'

$rand_query = new WP_Query($args);

echo '<ul class="aa_rp">';

while($rand_query->have_posts()) : $rand_query->the_post(); 
    echo '<li> <b><a href="' , the_permalink() , '" target="_blank" >' , substr(get_the_title(), 0, 22) , '..</a></b></li>';    


echo '</ul>';


and below is the code I use to make it into a shortcode:

function related_ad($atts, $content = null){
      extract(shortcode_atts(array('category' => 25), $atts));
      return aa_related_posts($category);
add_shortcode('related_ad', 'related_ad');

any help would be appreciated

  • I think I fixed this... I used: "wp_reset_postdata();" after the while loop and it seemed to have everything fixxed – rand_user91 May 31 '14 at 9:11

I added wp_reset_postdata(); at the end of the loop and it stopped pulling in comments from the loops

here is more about wp_reset_postdata()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.