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.
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&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:
<p> 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> </p>
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.
If 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