[resolved] new WP_Query function (4 posts)

  1. Beer
    Posted 7 years ago #

    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?

  2. Beer
    Posted 7 years ago #

    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?

  3. Beer
    Posted 7 years ago #

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


  4. jaredh123
    Posted 6 years ago #

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

    wp_reset_query(); to the rescue. :)

Topic Closed

This topic has been closed to new replies.

About this Topic