Order by Metabox time field

Hi,

I have a Metabox custom CPT which has a timepicker field in the format h:mm TT (so 9:45 AM).

I want to be able to sort the query loop by the time in each post but I can’t get anything to work. I’ve tried meta value and meta value numeric to order by.

Is this even possible without coding?

Thanks.

Hey @simon,

can you please show your time field’s setup? How / where do you specify the time format? Like this?

Do you specify the time format to output the value like this in the frontend? The backend? Or both?

Best,

André

Hi @aslotta ,

Yes, your screenshot is how I have it set for the front end display. I checked in the database and the values are being stored in that format too, so 9:45 AM. I can’t see where to change the database format but I guess for this to work, it would need some php to convert 12hr time to 24hr time and then echo the function in the meta value field.

Thanks,

Simon

Hey @simon,

yeah right. The Meta Box date field has an option to differentiate between the visual format and the save format. This does not apply to the time field though.

So I would not specify a specific time format in the field settings but use a Meta Box hook like this:

add_filter( 'rwmb_get_value', function( $value, $field ) {
    if ( is_array( $field ) && array_key_exists( 'id', $field ) && $field['id'] === 'custom_post_time' && ! empty( $value ) ) {
        $value = date( 'g:i A', strtotime( $value ) );
    }
    
    return $value;
}, 10, 2 );

Change custom_post_time to the name of your custom time field.

Then you should be able order by meta_value without issues:

CleanShot 2023-06-15 at 11.02.02

CleanShot 2023-06-15 at 11.02.19

Best,

André

1 Like

@aslotta you’re a star! Many thanks for the help.