I'm new to WordPress, and I'm having an issue with "The Loop." I have a sidebar on the left side of a page that's supposed to show recent posts from two categories. In the middle of the page, there should be content for that specific page. In the right column, there should be posts for a specific category.

Here's the problem: When I set up the left column, the middle column shows the posts content instead of the pages. See http://opachicago.com/wp/ if that doesn't make sense.

Here's my Loop codes:

Left Column (which should show Latest Posts):

<?php query_posts('category_name=News and Events, Uncategorized&showposts=5'); ?>
<?php if (have_posts()) : ?>
    <?php while (have_posts()) : the_post(); ?>   
        <p><?php the_time('M j') ?>: <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
    <?php endwhile; ?>
<?php endif; ?>

Middle Column (which should show Page content):

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
    <?php the_content(); ?>
<?php endwhile; ?>

1 Answer 1


Your page is behaving weirdly because you are using query_posts which clobbers the main query. Anything else on the page that depends on the main query has the wrong information after your query_posts runs. Don't use query_posts.

$qry = new WP_Query('category_name=News and Events, Uncategorized&showposts=5'); 
if ($qry->have_posts()) { 
  while ($qry->have_posts()) {
   // your Loop as normal
} else {
  // no posts found

At the end of this Loop the global $post variable will be set to the last item in the secondary Loop, and not to the current item in the main query Loop. You can demonstrate this with the following code:

var_dump($post->post_name); // main Loop
$qry = new WP_Query(array('post_type' => 'page','posts_per_page' => 1));
while ($qry->have_posts()) {
  var_dump($post->post_name); // secondary Loop
var_dump($post->post_name); // Still the secondary Loop

Since most Loops have the_post() at the beginning, that variable should be reset at that point, so resetting $post may not be necessary at all. To avoid that issue, I originally had wp_reset_query on the line following the end of the Loop, which does sort out $post, but as @Rarst points out here, that is overkill and wp_reset_postdata would be the better choice.



  • the codex is actually incorrect in the case of wp_reset_query(), you only need to use it if you've touched the $wp_query global. In this case wp_reset_postdata() is all you need (which wp_reset_query() itself calls after copying the wp_the_query global to wp_query).
    – Milo
    Commented May 31, 2013 at 14:45
  • @Milo : see the edit
    – s_ha_dum
    Commented May 31, 2013 at 16:16

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.