1

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.

  • 4
    order_by should be orderby – Milo Nov 13 '17 at 4:26
0

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' ), 
    ];

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.