How to order posts by modified date without using ‘query_posts’?

The question:

I have an example basic wordpress theme template here for you. First, please take a quick look at it to get an idea.

get_header(); ?>

    <div id="primary">
      <div id="content" role="main">

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

        <?php /* Start the Loop */ ?>
        <?php while ( have_posts() ) : the_post(); ?>

            /* Include the Post-Format-specific template for the content.
             * If you want to overload this in a child theme then include a file
             * called content-___.php (where ___ is the Post Format name) and that will be used instead.
            get_template_part( 'content', get_post_format() );

        <?php endwhile; ?>

        <?php reddle_content_nav( 'nav-below' ); ?>

      <?php else : ?>

        <article id="post-0" class="post no-results not-found">
          <header class="entry-header">
            <h1 class="entry-title"><?php _e( 'Nothing Found', 'reddle' ); ?></h1>
          </header><!-- .entry-header -->

          <div class="entry-content">
            <p><?php _e( 'It seems we can&rsquo;t find what you&rsquo;re looking for. Perhaps searching can help.', 'reddle' ); ?></p>
            <?php get_search_form(); ?>
          </div><!-- .entry-content -->
        </article><!-- #post-0 -->

      <?php endif; ?>

      </div><!-- #content -->
    </div><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

The simplest way to order posts by the last modified date is by adding this:

<?php query_posts($query_string . '&orderby=modified&order=desc'); ?>

Right above this:

<?php while ( have_posts() ) : the_post(); ?>

But that’s not what I want. I am told that it’s much better to use get_posts() or WP_Query() (see), than query_posts(). I do not know how to modify the code above as per the suggestions.

If would be very helpful if someone can give a pointer as to how I should use get_posts() or WP_Query() w.r.t the basic template above. Thanks.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

You haven’t specified where you want this alteration to apply to so I’ve applied it to just the home page. You may alter to fit where this filter applies to:

function wpse10691_alter_query( $query )
    if ( $query->is_main_query() && ( $query->is_home() || $query->is_search() || $query->is_archive() )  )
        $query->set( 'orderby', 'modified' );
        $query->set( 'order', 'desc' );
add_action( 'pre_get_posts', 'wpse10691_alter_query' );

Place code into theme functions.php or package into a plugin.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment