WordPress Tip: rewind_posts() Not Working
WordPress has a lot of very handy functions relating to the loop. One such function that can seem pointless, until you need to use it, is rewind_posts()
.
N.B. Just want to know why rewind_posts()
wasn’t working? Skip to the reason.
I recently used rewind_posts()
for a client’s site. The idea, which sadly I can’t show a picture of as of this moment, was to have a selection of post thumbnails on the left & load the post data into an area on the right when clicked.
To avoid writing a lot of AJAX related hooks, because the data required to swap out was fairly simple, and to save server resources I decided to use HTML 5’s very useful data (data-*
) attributes to store the data & swap it into the content area when the thumbnails were clicked. This worked without a hitch, but I didn’t want to have JavaScript as the initialization for the main content area. I couldn’t see the point as I could just have WordPress load the first post, it already had the data so why make things difficult.
So after the loop to get the thumbnails I used rewind_posts()
to reset the loop pointer back to the start of the posts array. This would allow me to output the first post’s data (again) without having to query the database again. If you’re an efficiency nut and prefer not to repeat yourself then this is awesome. The problem? It didn’t seem to work.
It Didn’t Work?
Nope. $wp_query->post
contained the correct data (it had been rewound correctly), but $post
didn’t making WordPress’ functions (the_title()
etc) output the wrong data.
Why Did That Happen?
Well it was my fault really. Because I was only outputting one post, I hadn’t wrote a loop. I just didn’t see the point. What I had totally forgotten was that WordPress requires you to at least run the_post()
to reinitialize the post data into the global $post
variable.
So what’s the moral of the story? Even if you only want to output 1 post & you don’t need a while loop, at least run the_post()
before you output any post data it will save you a major headache.