Why My WordPress Loop Was a Post Short

January 6th, 2014 - Posted by Steve Marks to PHP, Web Development.

Earlier today I was working on adding a blog to an existing site. This is a pretty standard task and one I’ve done many times in the past. This time it went a bit different than normal however as I got stuck in a situation that I just couldn’t figure out.

The Problem

I created the main blog page absolutely fine. I then moved onto creating the archive page. I setup an archive.php file and added the relevant code. After creating the archive page and viewing it on the website I noticed that there was a post missing from the list. It was set to show ten posts per page, but only nine were showing. A trimmed down version of my archive.php file looked like so:


while ( have_posts() ) :

    // Output post information here


There were plenty of published posts in WordPress so that wasn’t the problem. I decided to check the actual master query that WordPress was running to get the posts like so:

echo $GLOBALS['wp_query']->request;

This output an SQL query which I ran on the database which oddly returned the correct number of posts that I was expecting; in this case ten posts.

The Solution

After much trial and error, I ended up kicking myself when I found what the problem was, and I’m sure you will do the same.

The start of my problem was that I’d copied code from another file. As a result, notice how on line 3 of the code above I have referenced the_post();? By doing this I was essentially skipping over the first post by the time I got to the while() loop.

Once I’d removed the_post(); from the top of my file all the posts began to show as expected.

In my case it was the Archive file where this problem was occurring, but the same is true and could happen on any file where you loop through a list of posts automatically generated by WordPress (Taxonomies, Tags, Author Posts etc).

Tags: ,
This entry was posted on Monday, January 6th, 2014 at 1:42 pm by +Steve Marks and is filed under PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (1)
  1. You are a life saver, I was tearing my hair out. Thank you!