Orderby ACF custom field date don't work

前端 未结 3 1580
-上瘾入骨i
-上瘾入骨i 2021-01-25 09:03

I view the other post but I found nothing, I\'m on since 3 days :

I want display 3 \'evenements\' in the order ASC but 2018 is always before 2017



        
3条回答
  •  粉色の甜心
    2021-01-25 09:50

    As your date format is not in Y-m-d so you need to define your own logic for shorting

    function wh_posts_orderby($orderby, $query) {
        //Only for custom orderby key
        if ($query->get('orderby') != 'yyyymmdd_date_format')
            return $orderby;
        if (!( $order = $query->get('order') ))
            $order = 'ASC';
        global $wpdb;
        $fieldName = $wpdb->postmeta . '.meta_value';
        return "STR_TO_DATE(" . $fieldName . ", '%Y%m%d') " . $order;
    }
    
    add_filter('posts_orderby', 'wh_posts_orderby', 10, 2);
    

    Add the ^^above code to your active theme functions.php file.


    Now you can sort your post by date (format YYYYMMDD)

    $auj = date('Ymd');
    $args = [
        'category_name' => 'evenements',
        'posts_per_page' => 3,
        'meta_key' => 'date_de_fin',
        'orberby' => 'yyyymmdd_date_format', //check this line
        'order' => 'ASC',
        'meta_query' => [
            'relation' => 'AND', //added this
            [
                'key' => 'date_de_fin',
                'value' => $auj,
                'compare' => '>=',
                'type' => 'DATE'
            ],
        ]
    ];
    $queryEvent = new WP_Query($args);
    if ($queryEvent->have_posts()) :
        /* Start the Loop */
        while ($queryEvent->have_posts()) : $queryEvent->the_post();
    
        //you post
    
        endwhile;
    endif;
    

    Related answer How do I query posts and use the 'orderby' attribute to order posts in loop according to date 'meta_value'?

    Hope this helps!

提交回复
热议问题