Support » How-To and Troubleshooting » [Resolved] new WP_Query function

[Resolved] new WP_Query function

  • I have a function to get related posts based on tags.

    function getRelatedPosts($pid) {
    	# for use in the loop, list 5 post titles related to first tag on current post
    	$tags = wp_get_post_tags($pid);
    	if ($tags) {
    		echo '<h3>Related Posts</h3>';
    		$first_tag = $tags[0]->term_id;
    			'tag__in' => array($first_tag),
    			'post__not_in' => array($post->ID),
    		$my_query = new WP_Query($args);
    		if( $my_query->have_posts() ) {
    			while ($my_query->have_posts()) : $my_query->the_post(); ?>
    				<p><a href="<?php the_permalink() ?>" rel="bookmark"
    					title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p><?php
    	else print '<p>No related posts</p>';

    In single.php I am calling it.

    <p class="tags"><?php the_tags('<strong>Tagged:</strong> ', ', ', ''); ?></p>
    					<div id="related_posts"><?php getRelatedPosts($post->ID); ?></div>
    					<?php comments_template(); ?>

    It works great, but then the comments template thinks the current post is whatever the last result returned from getRelatedPosts() is, rather than the actual post. Anything after it actually.

    Any ideas?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Can anyone help me figure this out? I’m assuming a global value is being changed somewhere, so that comments_template() is getting the last value of the loop inside the previous function.

    Is it the new WP_Query() changing the values?
    Is it the $my_query->the_post() setting a global value?

    The answer was to add this at the end of the code.


    thanks, was scratching my head for about an hour till I found this.

    wp_reset_query(); to the rescue. 🙂

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘[Resolved] new WP_Query function’ is closed to new replies.
Skip to toolbar