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="<?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"> </div>';?>
</li>
<?php }
echo "</ul></div>";}}
wp_reset_query()
will reset the query to the original query WordPress did on this page. So if you somewhere calledquery_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.I think the problem here may have to do with the uses of including the global $post statement, as well as using get_posts.
you’re essentially calling for the posts twice, one with the new WP_Query (just to check the count of the posts returned), and the second time using get_posts.
the first time you check it, it has returned the posts under that main variable
$myquery->posts;
you also don’t want to use found_posts, as that doesn’t appear to return the right number. use $myquery->post_count instead.
once you get rid of the global $post, and the get_posts, change over the found_posts variable – you won’t have any more polution of data. i’ve used this:
and it didn’t ruin my data at all. though it’s a tiny bit more of a hassle since you can’t use the regular the_title, the_content, etc.. but you can use the get ones based on the id’s anyway – and if you need those specific filters for the regulars, you can always make use of them on the pulled content by applying them as well.