Skip to content

Instantly share code, notes, and snippets.

@billerickson
Created March 5, 2019 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save billerickson/ef928b326660d22fd80e58cf61abd879 to your computer and use it in GitHub Desktop.
Save billerickson/ef928b326660d22fd80e58cf61abd879 to your computer and use it in GitHub Desktop.
<?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>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment