SearchWP – Change sort order

<?php
/**
* Sort Search Query
*
*/
function ea_sort_search_query( $sql, $engine ) {
global $wpdb;
$options = array(
'date' => "ORDER BY {$wpdb->prefix}posts.post_date DESC",
'alpha' => "ORDER BY {$wpdb->prefix}posts.post_title ASC",
);
if( !empty( $_GET['search_sort'] ) && array_key_exists( $_GET['search_sort'], $options ) ) {
$sql = $options[ $_GET['search_sort'] ];
}
return $sql;
}
add_filter( 'searchwp_query_orderby', 'ea_sort_search_query', 10, 2 );
/**
* Search Filter
*
*/
function ea_search_filter() {
if( ! have_posts() )
return;
$options = array(
'relevance' => 'Relevance',
'date' => 'Date',
'alpha' => 'A-Z',
);
$current = !empty( $_GET['search_sort'] ) && array_key_exists( $_GET['search_sort'], $options ) ? $_GET['search_sort'] : 'relevance';
echo '<div class="search-sort">';
echo '<span class="label">Sorted by:</span>';
echo '<ul>';
foreach( $options as $key => $label ) {
$icon = $key == $current ? ea_icon( 'check' ) : false;
printf( '<li class="%s"><a href="%s">%s</a></li>',
ea_class( 'option', 'current', $key == $current ),
add_query_arg( array( 's' => get_search_query(), 'search_sort' => $key ), home_url() ),
$label . $icon
);
}
echo '</ul>';
echo '</div>';
}
view raw searchwp.php hosted with ❤ by GitHub

SearchWP

Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributing developer to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.

Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk