WP_Query sort by multiple custom fields
WP_Query has a meta_query
parameter to filter results by custom field values.
You can also use it for sorting if you give each meta_query element a named key.
Notice the names “featured” and “rating” within the meta_query, and how those names are also used within the orderby array.
$args = [
'post_type' => 'cars',
'post_status' => 'publish',
'meta_query' => [
'featured' => [
'key' => 'is_featured',
'compare' => 'EXISTS'
],
'rating' => [
'key' => 'avg_rating',
'compare' => 'EXISTS',
'type' => 'numeric'
]
],
'orderby' => [ 'featured' => 'DESC', 'rating' => 'DESC' ]
];
// Run the query at some point
$query = new WP_Query( $args );