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?