WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

So I got this to sort my posts and it works great:

<div class="sort">
   Sort by  
     <select onclick="if (this.value) { document.location = this.value; }">  
        <option value="" selected="selected">Latest first</option>  
        <option value="<?php echo $short_page_url; ?>?orderby=date">Oldest first</option>  
        <option value="<?php echo $short_page_url; ?>?orderby=title">Titles A-Z</option>  

But how can I have the order as separate dropdown/links to change between ASC and DESC? So it adds "&order=desc/asc" to the link when there's "?orderby=title/date" present?

share|improve this question
up vote 1 down vote accepted

I would do something like this:

<script type="text/javascript">
    function gup( name, default_value )
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = "[\\?&]"+name+"=([^&#]*)";
      var regex = new RegExp( regexS );
      var results = regex.exec( window.location.href );
      if( results == null )
        return default_value;
        return results[1];
    //here you can output default values for sortby and order by your php script
    var orderby = gup("orderby","");
    var order = gup("order","");
    function change_url() {
        var url = "<?php echo $short_page_url; ?>?orderby="+orderby+"&order="+order;
        document.location = url;

    //you still have to let javascript or php select the correct options
<div class="sort">
   Sort by  
     <select onclick="if (this.value) { orderby = this.value; change_url(); }">  
        <option value="" selected="selected">Latest first</option>  
        <option value="date">Oldest first</option>  
        <option value="title">Titles A-Z</option>  
     <select onclick="if (this.value) { order = this.value; change_url(); }">  
        <option value="asc">asc</option>  
        <option value="desc">desc</option>  
share|improve this answer
Thank you, this seems to be very close, but when the orderby is title the url goes to default ?orderby=date&order=asc when I try to select either asc or desc. – Andrew Mar 26 '12 at 9:36
I edited the code, so that it will take orderby and order from url parameters. – xaedes Mar 26 '12 at 12:12
notice : you still have to let javascript or php select the correct options. – xaedes Mar 26 '12 at 12:13
Very nice, thank you. Got it working perfectly with the updated code. – Andrew Mar 27 '12 at 7:15

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.