The function below is called from my index.php just below the main content block. Its purpose is to write out a link list of the latest posts. However, I need to reset the post object once this function has completed (or the sidebar query that follows thinks that the current post is the last post that gets executed by this function.)

How should I reset the post back to the current post of the page?

I’ve tried adding wp_reset_query() at the end of the function, but its not producing the results I want (produces multiple posts in the content area). Any help much appreciated.

function myFunction(){
    $catHidden=get_cat_ID('hidden');
    $myquery = new WP_Query();
    $myquery->query(array('cat' => "-$catHidden",'post__not_in' => get_option('sticky_posts')));
    $myrecentpostscount = $myquery->found_posts;
    if ($myrecentpostscount > 0){ ?>
        <div>
            <h4>Menu Title</h4>
            <ul>
            <?php 
            global $post;
            $myrecentposts = get_posts(array('post__not_in' => get_option('sticky_posts'), 'cat' => "-$catHidden",'numberposts' => get_option('latest_count')));
            foreach($myrecentposts as  $idxrecent=>$post) { ?>
                <li class="page_item">
                    <a href="https://wordpress.stackexchange.com/questions/18331/<?php the_permalink(); ?>"><?php if(has_post_thumbnail() && get_option('show_thumbs')) the_post_thumbnail('thumbnail', array('class' => 'alignleft', 'style' => 'margin:0 10px 0 0;')); ?><?php the_title(); ?></a>
                    <?php  
                        if(has_post_thumbnail() && get_option('show_thumbs')) echo '<div style="clear:both">&nbsp;</div>';?>
                </li>
            <?php } 
    echo "</ul></div>";}}

2 s
2

wp_reset_query() will reset the query to the original query WordPress did on this page. So if you somewhere called query_posts(), it will not reset back to that query, but to the “main” query.

You probably want to use wp_reset_postdata(), which resets the $post variable to the current post in $wp_query.

The best thing is to not overwrite the global $post variable in your function. All WordPress functions have variants that accept a post object, so there should be no need to use the global variable there.

Leave a Reply

Your email address will not be published. Required fields are marked *