Sort Posts by date or title

WordPress sorts Posts by date in descending order as default. But what if you want to order Posts by title? Say you have a Category where you archive movie reviews, and you want to sort this by title instead of by date. It’s easy to implement with a single line of code.

In the category.php of your Theme (if you don’t have a category.php you can duplicate index.php and rename it), add this line above the Loop (which usually starts with <?php if (have_posts()) : ?>):

<?php query_posts('orderby=title&amp;order=ASC'); ?>

You can extend this by adding links for which sort type you want. In your category.php add this where you want the links to appear:

 Sort by:
 <a href="<?php echo str_replace(('?'.$_SERVER['QUERY_STRING']), '', $_SERVER['REQUEST_URI']); ?>">Date</a>
 | <a href="<?php echo str_replace(('?'.$_SERVER['QUERY_STRING']), '', $_SERVER['REQUEST_URI']).'/?sort=title'; ?>">Title</a>

This will display like this: Sort by: Date | Title

Then use this code above the Loop:

<?php if($_GET['sort'] == 'title') query_posts('orderby=title&order=ASC'); ?>

This will sort Posts by date as default, but sort by title if the user clicks sort by title.

InfoIf you only want this function in one Category, you duplicate category.php and name it category-X.php, where X is the ID of the Category. (From version 2.9 of WordPress you can name it category-{category-slug}.php.)

4 thoughts on “Sort Posts by date or title

  1. Nelson Valdes

    I post by the date of the publication but would like within each date category to organize by the alphabetical order of the publication’s name.

    What should I do?


  2. Ron

    $order = ( get_query_var( ‘order’ ) ) ? get_query_var( ‘order’ ) : ‘desc’;
    $args = array(
    ‘post_type’ => ‘workshop’,
    ‘posts_per_page’ => 3,
    ‘order’ => $order

    $query_workshop = new WP_Query($args);


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.