WordPress change the order of posts through the standard loop

is it possible to order posts while keeping the standard WordPress loop intact (i.e. without having to create a whole new WP_Query?

By standard loop I mean:

Read More
<?php if ( have_posts() ) : ?>


            <?php /* The loop */ ?>
            <?php while ( have_posts() ) : the_post(); ?>

Can I specify the order within this code?

Related posts

Leave a Reply

2 comments

  1. As documented at query_posts function page:

    It is strongly recommended that you use the pre_get_posts filter
    instead, and alter the main query by checking is_main_query.

    You can add a new action on pre_get_posts in your theme functions.php file, like:

    function homepage_posts($query)
    {
        if ($query->is_home() && $query->is_main_query())
        {
            $query->set( 'orderby', 'title' );
        }
    }
    add_action('pre_get_posts', 'homepage_posts');
    
  2. wp_reset_query() is the way to go

    Example snippet

    <?php query_posts(array('orderby'=>'title','order'=>'DESC'));
    
    if ( have_posts() ) :
        while ( have_posts() ) : the_post(); ?>
            <a href="<?php the_permalink() ?>"><?php the_title() ?></a><br /><?php
        endwhile;
    endif;
    wp_reset_query();
    

    But keep in mind: query_posts() will change your main query and is not recommended. Only use if absolutely necessary (see query_posts: Caveats). Creating a new instance of WP_Query or get_posts() is preferred for secondary loops.