I would like to return search results in ascending order according to their numerical 'start date' value (e.g. 1970, 1971 etc.). However, some results do not have a value for this field and instead have a '-'; currently, these results are appearing first. Is there any way to have the results that have the '-' value appear at the end of the search results? My current code is below:

$options['ind_start'] = array( 'label' => 'Start Date (Earliest)', 'query_args' => array( 'orderby' => 'meta_value_num', 'meta_key' => 'start_date', 'order' => 'ASC', ), );

Thanks in advance!

  • Try 'orderby' => 'meta_value meta_value_num' and check for sorting numeric values first in your query.
    – Bhupen
    Commented Jan 28, 2020 at 11:48

1 Answer 1


Try to modify your query args to this:

    $options['ind_start'] = array(
        'label' => 'Start Date (Earliest)',
        'query_args' => array(
            'meta_query' => array(
                'start_date_query' => array(
                    'key' => 'start_date',
                    'compare' => 'EXISTS', // Optional

meta_query - will include only posts with any start_date value.

Then add a WP query order filter:

function my_order_filter($orderby, $obj){
    global $wpdb;

    // Put here some conditional logic if you want to apply this only for a specific query.

    $new_order_query_part = "{$wpdb->postmeta}.meta_value = '-' ASC, {$wpdb->postmeta}.meta_value ASC ";
    if( trim($orderby) ){
        $orderby = $new_order_query_part . ', ' . $orderby;
    } else {
        $orderby = $new_order_query_part;

    return $orderby;
add_filter( 'posts_orderby_request', 'my_order_filter', 10, 2 );

This filter will be applied to all queries. If you need to add order feature only to a specific query, then use some conditional filtering before applying the new order to the request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.