How do I get wordpress to override a previous posts query?

I’ve got a page that has a category list at the top, and should normally list posts below it. The category list is created using:

<?php $display_categories = array( 4, 7, 8, 9, 21, 1); $i = 1;
    foreach ( $display_categories as $category ) { ?>
        <div>
            <?php single_cat_title(); ?> //etc
        </div>
    <?php } 
?>

However, this seems to make the post loop order posts by category. I want it to ignore category ordering and order by date in descending order. I’ve created a new WP_Query since according to the docs you can’t use query_posts() twice, so just in case.

Read More
<?php $q = new WP_Query( "cat=-1&showposts=15&orderby=date&order=DESC" );
    if ( $q->have_posts() ) : 
        while ( $q->have_posts() ) : $q->the_post(); ?>
            the_title(); // etc
        endwhile; 
    endif; 
?>

However, this still seems to be ordered by category (the same order as the list above) and then by date, as opposed to just by date.

Related posts

Leave a Reply

3 comments

  1. I’ve had problems with this before as well.

    Try this:

    <?php
        global $post;
        $myposts = get_posts( 'numberposts=5' );
        foreach( $myposts as $post ) : setup_postdata( $post ); ?>
            <div <?php post_class(); ?>>
                <div class="title">
                    <h2>
                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                    </h2>
                    <p class="small"><?php the_time( 'F j, Y' ); ?> by <?php the_author(); ?></p>
                 </div>
                 <?php the_excerpt(); ?>
             </div>
         <?php endforeach; 
     ?> 
    

    The important line is global $post;.

    That should reset your global query. The setup_postdata($post) method is necessary to give you access to functions like the_author() or the_content().

    -Chris

  2. query_posts is finicky sometimes. Try something like this and see if it works:

    query_posts(array('category__not_in'=>array(1),
                      'showposts'=>15,
                      'orderby'=>date,
                      'order'=>DESC));
    

    Since that’s not the issue, try adding update_post_caches($posts) to the second loop, like this:

    <?php $q = new WP_Query("cat=-1&showposts=15&orderby=date&order=DESC");
    if ( $q->have_posts() ) : while ( $q->have_posts() ) : $q->the_post(); update_post_caches($posts); ?>
    the_title(); // etc
    endwhile; endif; ?>
    

    Supposedly this solves some plugin problems.