Home › Forums › Product Support Forums › Ajax Search Pro for WordPress Support › Implement a sorting dropdown › Reply To: Implement a sorting dropdown
September 29, 2025 at 9:50 am
#55605
Keymaster
Okay.
So say you have a single drop-down, which appends the “the_order” query variable, so the URL looks like this “…&the_order=yourvalue” on the results page. Then it is accessed on page load within the code via the $_GET['the_order'].
Here is a custom code snippet which handles that, it has examples for id, date, title, relevance and even string and numeric custom field based ordering:
// Custom ordering
add_filter(
'asp_query_args',
function ( $args ) {
// The values allowed in the the_ordering variable
$allowed_orderings = array(
'relevance',
'id',
'id_reverse',
'date',
'date_reverse',
'alpha',
'alpha_reverse',
'numeric_custom_field',
'string_custom_field',
);
if ( !isset($_GET['the_order']) ) {
return $args;
}
$ordering = sanitize_text_field( wp_unslash( $_GET['the_order'] ) );
if ( !in_array($ordering, $allowed_orderings, true) ) {
return $args;
}
switch ( $ordering ) {
case 'id':
$args['post_primary_order'] = 'id DESC';
break;
case 'id_reverse':
$args['post_primary_order'] = 'id ASC';
break;
case 'date':
$args['post_primary_order'] = 'post_date DESC';
break;
case 'date_reverse':
$args['post_primary_order'] = 'post_date ASC';
break;
case 'alpha':
$args['post_primary_order'] = 'post_title DESC';
break;
case 'alpha_reverse':
$args['post_primary_order'] = 'post_title ASC';
break;
case 'numeric_custom_field':
$args['post_primary_order'] = 'customfp DESC';
$args['post_primary_order_metatype'] = 'numeric';
$args['_post_primary_order_metakey'] = 'custom_field_name';
break;
case 'string_custom_field':
$args['post_primary_order'] = 'customfp DESC';
$args['post_primary_order_metatype'] = 'string';
$args['_post_primary_order_metakey'] = 'custom_field_name';
break;
case 'relevance':
default:
$args['post_primary_order'] = 'relevance DESC';
break;
}
return $args;
}
);