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

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

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


<?php 

$new_query
= $HTTP_GET_VARS;
if (
$order == 'ASC')
{
    
$new_query['order'] = 'DESC';
}
else
{
    
$new_query['order'] = 'ASC';
}
$new_query_url=$PHP_SELF.'?'.http_build_query($new_query);
?>

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

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


4 responses to “Reverse Order Button”

  1. ‘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.