0

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>  
     </select>
</div>

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?

1 Answer 1

1

I would do something like this:

<script type="text/javascript">
    //http://www.netlobo.com/url_query_string_javascript.html
    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;
      else
        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
</script>
<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>
   Order 
     <select onclick="if (this.value) { order = this.value; change_url(); }">  
        <option value="asc">asc</option>  
        <option value="desc">desc</option>  
     </select>
</div>
4
  • 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, 2012 at 9:36
  • I edited the code, so that it will take orderby and order from url parameters.
    – xaedes
    Mar 26, 2012 at 12:12
  • notice : you still have to let javascript or php select the correct options.
    – xaedes
    Mar 26, 2012 at 12:13
  • Very nice, thank you. Got it working perfectly with the updated code.
    – Andrew
    Mar 27, 2012 at 7:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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