Sort Posts Best Practice

I have a custom post type “Properties”.

These properties posts are being listed out on page “Properties For Let”.

Read More

Each property post has various custom meta including price, and number of bedrooms.

The properties will initially be listed in the order defined by the original wp query I set.

However at the top of the page I wish to have links that upon click will sort the posts by Price, Date Added and Number Of Bedrooms.

What is the best practice for doing this? I have seen people advise on addin query strings to URLs etc but would like some solid advice

Thanks in advance for any help

John

Related posts

Leave a Reply

2 comments

  1. The function add_query_arg adds or replaces ‘GET’ parameters in a given (or the current) url.

    For instance, suppose someone is viewing the page:

    http://www.example.com?order=ASC&orderby=meta_value_num&meta_key=price

    (viewing properties in price order). Then the url

    $url = add_query_arg(array('meta_key'=>'bedrooms','orderby'=>'meta_value_num'));
    

    Would give you

    http://www.example.com?order=ASC&orderby=meta_value_num&meta_key=bedrooms

    (the url to order properties by number of bedrooms).

    E.g:

     <?php
       $by_rooms= esc_url(add_query_arg(array('meta_key'=>'bedrooms','orderby'=>'meta_value_num')));
       $by_price = esc_url(add_query_arg(array('meta_key'=>'price','orderby'=>'meta_value_num')));
       $by_data = esc_url(add_query_arg(array('meta_key'=>false,'orderby'=>'date')));
     ?>
    
     <ul>
        <li> <a href="<?php echo $by_price;?>">Order by price</a></li>
        <li> <a href="<?php echo $by_rooms;?>">Order by rooms</a></li>
        <li> <a href="<?php echo $by_date;?>">Order by date</a></li>
     </ul>