Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

How to display posts with 'Event' custom type ordered by 'Start_Hour' and then by 'Start_Minute'?

'Start_Hour' and 'Start_Minute' are numeric custom fields.

I tried this, but it doesn't work:

$args = array(
  'post_type'=>'Events',
  'orderby' => 'meta_value',
  'meta_key' => 'Start_Hour Start_Minute',
  'order' => 'ASC'
);
$loop = new WP_Query( $args );
share|improve this question
add comment

2 Answers

when you use 'meta_key' => 'Start_Hour Start_Minute' then the query looks for posts with a custom field named Start_Hour Start_Minute together so that is why its not working for you.

But there is a way to order by multiple custom fields using posts_orderby filter hook, so first create a function that will add your orderby fields like so:

function orderbyreplace($orderby ) {
  global $wpdb;
    return str_replace($wpdb->prefix.'postmeta.meta_value', 'mt1.meta_value, mt2.meta_value ASC', $orderby);
}

then set your args as:

$args = array(
  'post_type'=>'Events',
  'orderby' => 'meta_value',
  'meta_key' => 'Start_Hour',
  'meta_query' => array(
        array(
            'key' => 'Start_Hour',
            'value' => '0',
            'type' => 'NUMERIC',
            'compare' => '!='
        ),
        array(
            'key' => 'Start_Minute',
            'value' => '0',
            'type' => 'NUMERIC',
            'compare' => '!='
        )
    )
);

See how i use the meta_query which will join both custom fields and all that is left is to hook your orderbyreplace function just before your query so:

add_filter('posts_orderby','orderbyreplace');
$loop = new WP_Query( $args );
remove_filter('posts_orderby','orderbyreplace');
share|improve this answer
add comment
up vote 1 down vote accepted

Thanks to Bainternet I found the solution:

function orderbyreplace($orderby) {
    return str_replace('menu_order', 'mt1.meta_value, mt2.meta_value', $orderby);
}

and...

$args = array(
  'post_type'=>'Events',
  'orderby' => 'menu_order',
  'order' => 'ASC',
  'meta_query' => array(
        array(
            'key' => 'Start_Hour',
            'value' => '',
            'compare' => 'LIKE'
        ),
        array(
            'key' => 'Start_Minute',
            'value' => '',
            'compare' => 'LIKE'
        )
    )
);
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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