• I’m trying to query custom posts ordering by a meta_key. But after WP_Query running, there isn’t any change in sql query inside the order clause.

        $args = array(
        'post_type'   => 'event',
        'post_status' => 'publish',
    
        'meta_key' => '_start_eventtimestamp',
        'orderby' => 'meta_value_datetime',
        'order' => 'ASC',
    
        'meta_query' => array(
            array(
                'key' => '_start_eventtimestamp',
                'value' => date('Ymd'),
                'compare' => '>='
            )
        ),
    
        'posts_per_page' => '7',
        );
    
        $event_query = new WP_Query( $args );

    And when I get the generated query I got this:

        SELECT SQL_CALC_FOUND_ROWS wp_posts.ID 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_postmeta.meta_key = '_start_eventtimestamp'
         AND ( ( mt1.meta_key = '_start_eventtimestamp' AND mt1.meta_value >= '20160930' ) ) )
         AND wp_posts.post_type = 'event' AND ((wp_posts.post_status = 'publish'))
         GROUP BY wp_posts.ID ORDER BY wp_posts.menu_order ASC LIMIT 0, 7

    The order clause suffered no change.
    Is there wrong in my script of order by meta_key?

    • This topic was modified 8 years, 5 months ago by rafael.
Viewing 1 replies (of 1 total)
  • Hello @soufraz,
    Please change the order of these two lines

    'meta_key' => '_start_eventtimestamp',
    'orderby' => 'meta_value_datetime',

    to

    'orderby' => 'meta_value_datetime',
    'meta_key' => '_start_eventtimestamp',

    Changing the order might solve your issue.
    Thanks.

Viewing 1 replies (of 1 total)
  • The topic ‘Order by meta_key in custom post type doesn’t affect the query’ is closed to new replies.