WordPress/ACF: Sort Posts by multiple fields

i have posts with two advanced custom fields “name” and “surname”
and i need to query the post to have it in the right sequece.
name / surnname / title

like this:
Doe, Joen, Title

Read More

my query looks like this

$args = array(

'numberposts' => -1,
'post_type' => array ('events'),
'meta_key' => 'name',
'orderby' => 'meta_value',
'order' => 'ASC',
'meta_query'=> array(
    array(
        'key' => 'date',
        'compare' => '<',
        'value' => $today,
        'type' => 'DATE',
        )),

);

How can I order the posts in the right way?

i tried something like this:

'orderby' => 'meta_value surname',

but i think this dont work with custom fields

thanks!!!

++

thanks alot Mukesh!
this works (i hope so…)

    SELECT SQL_CALC_FOUND_ROWS * FROM wpdev_posts
    INNER JOIN wpdev_postmeta ON ( wpdev_posts.ID = post_id  ) 
    INNER JOIN wpdev_postmeta AS mt1 ON ( wpdev_posts.ID = mt1.post_id ) 
    INNER JOIN wpdev_postmeta AS mt2 ON ( wpdev_posts.ID = mt2.post_id ) 
    WHERE 1=1 AND ( wpdev_postmeta.meta_key = 'referent_name' )     AND ( mt1.meta_key = 'referent_vorname' )     

    AND ( ( mt2.meta_key = 'datum' AND CAST(mt2.meta_value AS DATE) < 20190527 ) ) 
    AND wpdev_posts.post_type = 'veranstaltungen' 
    AND (wpdev_posts.post_status = 'publish' 
    OR wpdev_posts.post_status = 'pending' OR wpdev_posts.post_status = 'confirmed' 
    OR wpdev_posts.post_status = 'paid' OR wpdev_posts.post_status = 'complete' 
    OR wpdev_posts.post_status = 'private') 


    GROUP BY wpdev_posts.ID 
    ORDER BY wpdev_postmeta.meta_value ASC, mt1.meta_value ASC, post_title ASC      

Related posts

1 comment

  1. Try below code it will help to you.

    <?php 
        global $wpdb;
         $query = "SELECT SQL_CALC_FOUND_ROWS * FROM $wpdb->posts
                     INNER JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id ) 
                     INNER JOIN $wpdb->postmeta AS mt1 ON ( wp_posts.ID = mt12.post_id ) 
                     INNER JOIN $wpdb->postmeta AS mt2 ON ( wp_posts.ID = mt2.post_id ) 
                     WHERE 1=1 AND ( $wpdb->postmeta.meta_key = 'name' ) AND ( mt1.meta_key = 'surname' ) 
                     AND ( ( mt2.meta_key = 'date' AND CAST(mt2.meta_value AS DATE) < $today ) ) ) 
                     AND $wpdb->posts.post_type = 'events' AND ($wpdb->posts.post_status = 'publish' 
                     OR $wpdb->posts.post_status = 'pending' OR $wpdb->posts.post_status = 'confirmed' 
                     OR $wpdb->posts.post_status = 'paid' OR $wpdb->posts.post_status = 'complete' 
                     OR $wpdb->posts.post_status = 'private') 
                     GROUP BY wp_posts.ID 
                     ORDER BY wp_postmeta.meta_value ASC, mt1.meta_value ASC ";
    
        $posts = $wpdb->get_results($query, object);
        echo '<pre>';print_r($posts);
    ?>
    

Comments are closed.