0

I have a custom post type field that I am storing data in called football_game_datetime.

Example format and values for this field are examples like: "2013-10-31 14:00:00", "2013-09-16 20:00:00", "2013-09-30 22:00:00".

The code I am using is the following, but it isn't doing what I thought it should be doing:

$mypost =
array(
    'post_type' => 'football_games',
    'meta_query' => array(
           array(
                'order'=>'DESC',
                'orderby' => 'meta_value_num',
                'meta_key' => 'football_game_datetime'
           )
    )
);
$loop = new WP_Query( $mypost );
3

'orderby' => 'meta_value_num' will try to force the value to a number by adding 0. In other words, "2013-09-30 22:00:00"+0 When I tested that both PHP and MySQL converted the string to 2013, which is not what you want.

That particular date format, and only that date format, will sort correctly if you just leave it alone. That is, it will sort matching a human calendar. Don't use meta_value_num. You don't have a number. You have a string. Just use meta_value.

Secondly, order and orderby are not valid inside a meta_query those need to be outside the meta_query, and in fact, I don't think you need the meta_query at all.

$mypost =
array(
    'post_type' => 'football_games',
    'order'=>'DESC',
    'orderby' => 'meta_value',
    'meta_key' => 'football_game_datetime'
);
$loop = new WP_Query( $mypost );

What you have is essentially, this example from the Codex:

$query = new WP_Query( array ( 'post_type' => 'product', 'orderby' => 'meta_value', 'meta_key' => 'price' ) );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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