sort post in custom post type by multiple custom fields acf

I have 4 text field type in a custom post type, these are brand_fbn,model_fbn,year_fbn and plate_number. I want to sort the post, by brand_fbnmodel_fbnyear_fbnplate_number. But im stuck with that,

this is my code(error)

Read More
                        $ins = new WP_Query(array(
                            "post_type" =>      "application-list",
                            "author"    =>      $current_user->ID,
                            "meta_key"      =>  array("year_fbn","plate_number"),
                            "orderby"       =>  "meta_value ",
                            "order"         =>  "ASC"
                        ));

I know this line wont work, "meta_key"=>array("year_fbn","plate_number"), can someone help me. thanks

Related posts

1 comment

  1. You’ll need to query for the meta fields so that they are JOINed within WP_Query and then use the posts_orderby filter to order your results by those meta fields – the alias use will be in the format mt1.meta_value.

    // Function to replace the order by clause in the SQL generated by WP_Query
    function custom_order_by( $order_by ){
        return str_replace( 
            'menu_order', 
            'mt1.meta_value, mt2.meta_value, mt3.meta_value, mt4.meta_value',
            $order_by 
        );
    }
    
    // args for WP_Query
    $args = array(
        "post_type"   => "application-list",
        "author"      => $current_user->ID,
        "meta_query"  => array(
            array( 
                "key"     => "brand_fbn", 
                "compare" => "LIKE",
                "value"   => ""
            ),
            array( 
                "key"     => "model_fbn", 
                "compare" => "LIKE",
                "value"   => ""
            ),
            array( 
                "key"     => "year_fbn", 
                "compare" => "LIKE",
                "value"   => ""
            ),
            array( 
                "key"     => "plate_number", 
                "compare" => "LIKE",
                "value"   => ""
            )
        )
    );
    
    // add filter to modify order by clause
    add_filter( 'posts_orderby', 'custom_order_by' );
    // run the WP_Query
    $ins = new WP_Query( $args );
    // remove the filter so that other queries aren't affected.
    remove_filter( 'posts_orderby', 'custom_order_by' );
    

Comments are closed.