WordPress Tip: rewind_posts() Not Working

/ Wordpress / by Paul Robinson / 0 comments
This post was published back on December 19, 2012 and may be outdated. Please use caution when following older tutorials or using older code. After reading be sure to check for newer procedures or updates to code.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I'll keep your WordPress site up-to-date and working to its best.

Find out more