Losing my mind – is it ever correct to use wp_reset_postdata?
-
Suppose you were writing a custom shortcode or block that includes a custom query. The following type of custom loop has always been a standard pattern:
global $post; $results = get_posts(...); foreach ($results as $post) { setup_postdata($post); // do something } wp_reset_postdata();
You’ll see that type of code throughout numerous tutorials (and existing plugins). I’ve used it numerous times myself.
Have I come to a correct realization that that code should never be used?
The reason being because this block may be processed outside the loop. The most common occasion is when using excerpts. For example, suppose your theme has a static homepage with another custom block (or perhaps it’s a widget in your sidebar) which loads the most recent blog post on the site and calls the_excerpt() followed by the_permalink().
While calling the_excerpt(), it processes your custom block, and wp_reset_postdata() will reset the post variable incorrectly to the static homepage (original query) – so the_permalink() will print the homepage URL.
It seems the only solution is to avoid using wp_reset_postdata entirely, instead using something like:
$saved_post = $post; // now run your custom code $post = $saved_post; setup_postdata($post);
I’ve been developing WordPress sites for a long time, and have only just stumbled over this edge case – it’s driving me a bit made that it seems like the standard code that WordPress typically recommends has been incorrect all this time, unless I’m missing something?
- The topic ‘Losing my mind – is it ever correct to use wp_reset_postdata?’ is closed to new replies.