Reverse Order Button

I coded up this nice little button that allows you to reverse the current sort order of posts, so you can look at earliest or latest posts first. Right now I have the button just below the page header – try it out. It’s a nice, clean, satifying bit of code. I’m running WordPress-1.0.1, but it will likely work with earlier versions too. Read on for details.

The nice thing about this code is that is works on whatever set of posts you’re currently looking at. So if you’ve done a search, or a date query, clicked a category, whatever – the button resorts those posts only. The key to that feature is PHP’s http_build_query() function, which is new and not yet available on my server. Luckily there is a simple implementation you can put in your my-hacks.php file:

// This is being added to PHP. So use system function if it exists

http_build_query($formdata, $numeric_prefix = ''){
_http_build_query($formdata, $numeric_prefix = '',$key_prefix=''){
$numeric_prefix != '' && !is_numeric($numeric_prefix)){
       } else {
$prefix = '';
is_array($formdata)) return '';
$formdata as $key => $val){
$str != '') $str.='&';
$key_prefix != '') {
$mykey = $key_prefix."[$key]";
           } else {
           } else {

With that done, all that’s needed is this bit of code in index.php:


if (
$order == 'ASC')
$new_query['order'] = 'DESC';
$new_query['order'] = 'ASC';

<form action="">
    value="Reverse Order"
    onclick="location='<?php echo $new_query_uri ?>'"
    title="Click to reverse the sort order of the current set of posts."

Easy! The same technique should work to make controls for other query string arguments too. Go to town!

Get new posts in your inbox

4 thoughts on “Reverse Order Button

  1. i got through the first sentence of this and a “nerdy” feeling. anyone else get that? just me?

  2. ‘cuz it’z a bit computery / nerdy. it’s ok though.
    yer leaving, i’ll prolly get desperate and have to read it.

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.