0

I'm building my own theme. I have a page set for my blog (with a template that I made) which I'd like to just display a few of my posts. It uses the following loop:

<?php
   query_posts('post_type=post');
   if (have_posts()) {
      while (have_posts()) {
?>

<div class="blog_post">
   <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
   <div class="entry_date"><?php the_time('F jS, Y') ?></div>
   <?php
      the_post();
      the_content();
   ?>
</div>

<?php
      }
   }
?>

The titles of my posts are "First Post, Second Post, Third Post, and Fourth Post" respectively. When the posts are displayed on the blog page, they are displayed in the correct order, but the titles of the posts are incorrect. The first post's title reads: "Second Post". The second post's title is: "Third Post", and so on until the last (most recent) post which has the title: "Blog" (the page title). What happened to the titles that they got so screwed up?

What I've Tried: I've researched this a lot before I came here. I tried using get_the_title() instead but that lead to no titles being displayed. I've also tried using the_title_attribute() to no avail. I also understand that I shouldn't be using query_posts for this loop but I'm unsure which is the correct method to use for getting the posts in this particular case. Most of the info I've read was unclear though and didn't seem to fix the issue.

Any help is greatly appreciated.

1 Answer 1

3

Welcome the the WordPress Stack Exchange and congrats on your first post! First off, you may not want to use query_posts() here. Second off - the_post() needs to be before the_title() as it sets up all the posts functions such as the_title(), the_permalink() etc. and queues the next post in your while loop. Your Loop should look like this:

<?php
   query_posts('post_type=post');
   if (have_posts()) {
      while (have_posts()) { the_post();
?>

<div class="blog_post">
   <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
   <div class="entry_date"><?php the_time('F jS, Y') ?></div>
   <?php the_content(); ?>
</div>

<?php
      }
   }
?>

Hopefully that helps, here's some more information on The Wordpress Loop and setting up post data.

Read More about the_post().

Read More about The Loop.

1
  • Thanks! I just figured that out like two seconds before you posted your answer but I feel like it's good for other people to know who may run into the same problem. Thanks as well for the clarification of the query_posts() function. I'll be looking into which is the correct function to use. Commented Dec 17, 2014 at 23:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.