2

I have custom post type event which has custom field event_date. The date format for this field is set to Ymd.

I'm trying to get posts in order of event_date

Here is the code to pull the posts in that order

$today = date('Ymd');

$args = array (
    'post_type'             => array( 'event' ),
    'posts_per_page'        => '-1',
    'order'                 => 'ASC',
    'orderby'              =>'meta_value', // also tried having meta_value_num but that didn't worked as well
    'meta_key'              =>'event_date',
    'meta_query' => array(
        array(
            'key'       => 'event_date',
            'compare'   => '>=',
            'value'     => $today,
        )
    ),
    'suppress_filters' => true
);
/*
global $wp_filter;
var_dump( $wp_filter['posts_orderby'] );die;
This returns NULL as well
*/


    $query = new WP_Query( $args );
    echo '<pre>';
    var_dump($query->request);die;

But the $query->request shows the ORDER BY as post_date rahter than my supplied query. Here is the dump of request

string(681) "SELECT   wp_posts.* FROM wp_posts  INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )  INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) WHERE 1=1  AND ( 
  wp_posts.ID NOT IN (
                SELECT object_id
                FROM wp_term_relationships
                WHERE term_taxonomy_id IN (11)
            )
) AND ( 
  wp_postmeta.meta_key = 'event_date' 
  AND 
  ( 
    ( mt1.meta_key = 'event_date' AND mt1.meta_value >= '20171113' )
  )
) AND wp_posts.post_type = 'event' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date ASC "

can't order by the event_date. What am i doing wrong?? Even tried by having

remove_all_filters('posts_orderby');

before the wp_query still same result.

NOTE: Posted this in stackoverflow but couldn't get answer so this is a repost.

1
  • 4
    order_by should be orderby
    – Milo
    Commented Nov 13, 2017 at 4:26

1 Answer 1

4

There seems to be a bug in Wordpress building the query. I had this exact same issue today, using ACF Pro. I passed an array to orderby, and it worked. This is my code:

$args = [
        'post_type'         => 'event',
        'meta_query'        => array(
                    'key'       => 'event_date',
                    'value'     => date('Ymd'),
                    'type'      => 'DATE',
                    'compare'   => '>='
        ),
        'meta_key'  => 'event_date',
        'orderby' => array( 'meta_value' => 'ASC' ), 
    ];
1
  • Had the same issue, the above code worked for me. Thank you! Commented Jul 28, 2019 at 10:34

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.