SearchWP – Change sort order

/**
 * Sort Search Query
 * @link https://www.billerickson.net/code/searchwp-change-sort-order/
 */
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
 * @link https://www.billerickson.net/code/searchwp-change-sort-order/
 */
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>';
}

Bill Erickson

Bill Erickson is the co-founder and lead developer at CultivateWP, a WordPress agency focusing on high performance sites for web publishers.

About Me
Ready to upgrade your website?

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

Let's Talk