Sorting search results with custom dropdown

I have the following select dropdown code for sorting on my search results page (search.php) that works for custom fields.

<div id=”sortby”> SORT BY: &nbsp;
<select class=”dropdown-class” name=”sort-posts” id=”sortbox” onchange=”document.location.href=location.href+this.options[this.selectedIndex].value;”>
<option disabled>Sort by</option>
<option value=”&orderby=date&order=DESC”>Newest</option>
<option value=”&orderby=date&order=ASC”>Oldest</option>
<option value=”&orderby=property_price2&order=DESC”>Most Expensive</option>
<option value=”&orderby=property_price2&order=ASC”>Least Expensive</option>
<option value=”&orderby=area2&order=DESC”>Largest</option>
<option value=”&orderby=area2&order=ASC”>Smallest</option>

I also I have the following code in my functions.php to make this work —

function wpse139657_orderby(){
if( isset($_GET[‘orderby’]) ){
$order = $_GET[‘order’] or ‘DESC’;
set_query_var(‘orderby’, ‘meta_value_num’);
set_query_var(‘orderby’, ‘date’);
set_query_var(‘meta_type’, ‘numeric’);
set_query_var(‘meta_key’, $_GET[‘orderby’]);
set_query_var(‘order’, $order);


It works when sorting by price or area, but it doesn’t work when trying to sort by the date.

I’ve tried different meta_keys for the date ie – publish_date, the_date, date, get_the_date, etc..

What am I missing?

Also if use the sort on ie – the 3rd page, the results reload and keep me on the 3rd page, how can I bring the user to the 1st page of results after sorting?

Read more here:: Sorting search results with custom dropdown

Leave a Reply

Your email address will not be published. Required fields are marked *