wordpress query in header won’t reset and corrupts other loops

In a template part in my header, I have the following code:

$args = array('post_type'=>'weather_today','orderby'=>'ID','order'=>'ASC','posts_per_page'=>1);
$query = new WP_Query($args);
$html;
if ($query->have_posts()){
$posts = $query->posts;
foreach($posts as $post) {
$html = $post->post_content;
}
}
wp_reset_postdata();
?>

My understanding is that wp_reset_postdata is what I need to reset the query, according to this answer: wp_reset_postdata() or wp_reset_query() after a custom loop?

I tried wp_reset_query() as well but neither works, as my other template parts are getting affected by the header code. As an example, when I do my single.php template and do this:

while ( have_posts() ) : the_post();
the_title();
endwhile; 

I get the weather_today post type title, not the single.php post.

I got around this in my category.php by doing this:

$current_category_id = get_query_var('cat');
$current_category_obj = get_category($current_category_id);
$args = array('orderby'=>'ID','order'=>'DSC','posts_per_page'=>8,'cat'=>$current_category_id);
$query = new WP_Query($args);

And then looping through, but I don’t want to keep moving around the issue that my header query isn’t resetting. I don’t know a similar work around for single.php and it seems unideal to do a WP Query on a template file that is supposed to instantiate it’s own query – like how single.php should pick up on the post that is single given the url, or however it works internally.

How do I do the query I need in my header and still be able to have the other theme/template files work as expected?

1 Answer
1

Two issues here.

First, you’re not using the loop properly. Instead of the foreach use while ( $query->have_posts() ) { $query->the_post(); //etc.

Secondly, in using foreach($posts as $post) you are overwriting the global $post variable, so if you really must use foreach then use a different variable name!

Leave a Comment