-
-
Notifications
You must be signed in to change notification settings - Fork 513
Reset post data after Timber loops. #1771
Description
This issue picks up on the issue described in #1639 (comment), because I think it’s a separate problem.
Timber updates the $post global whenever it loops over a collection of posts. When a WordPress function is called after a Timber loop, the WordPress function that maybe relies on the $post global as well could return an unexpected result.
Here’s an example: I display a list of related posts below the post content in a single template with a loop over a Timber post collection. After the related posts, I display the post comments through the comments_template() function. The displayed comments will not be the comments of the displayed post, but the comments from the last of the related posts.
The easiest way to circumvent this for now is to call wp_reset_postdata() right after the Timber loop:
{% for post in posts_related %}
{# Display post #}
{% endfor %}
{% do fn('wp_reset_postdata') %}
{% if post.comments_open or post.comment_count > 0 %}
{% do fn('comments_template') %}
{% endif %}The wp_reset_postdata() function overwrites the $post global and sets up the post data for the displayed post again:
$GLOBALS['post'] = $wp_query->post;
setup_postdata( $wp_query->post );So I’m asking myself: For better compatibility, should Timber automatically reset post data after Timber loops? And how can we do this?
Here are some thoughts:
- Do we really need to set the post global when looping over a collection of posts? I’d say yes, because inside the loop, you could call WordPress functions that rely on the
$postglobal. - A good solution might be to run
wp_reset_postdata()right after the loop. But is it possible to run a function after the last run inTimber\PostsIterator? I couldn’t find any solution for this. - Alternatively, would it be enough to do this in Twig only? Because there we could probably write a Twig extension with a custom
NodeVisitorthat runs the function after the last for-loop. - Would it be enough to document this properly?
What should we go for? And are there other approaches?
I’m marking this as a future issue to tackle.