Home › Forums › General Issues › orderby multiple field values
Hello all, I have a custom post type which I need to order in a specific order. These custom fields are Best Seller, and New, based on these values, it shows a tag on the post. New is not related to the post date just to make that clear. I want to query all the posts for this custom post type, but order them in the following order Best Seller, New, the rest of the posts.
Here is what I have tried, but the order is wrong, I can’t figure out how to get this query to work and order the posts how I want.
$args = array(
'post_type' => 'products',
'post_status' => 'publish',
'showposts' => '-1',
'tax_query' => array(
array(
'taxonomy' => 'products_category',
'field' => 'id',
'terms' => $termId,
),
),
'paged' => $paged,
'meta_query' => array(
array(
'relation' => 'OR',
'best_seller' => array(
'key' => 'best_seller',
'value' => 1,
'compare' => '>='
),
'new' => array(
'key' => 'new',
'value' => 1,
'compare' => '>='
),
'others_best_seller' => array(
'key' => 'best_seller',
'value' => 1,
'compare' => '<'
),
'others_new' => array(
'key' => 'new',
'value' => 1,
'compare' => '<'
),
)
),
'orderby' => array(
'best_seller' => 'DESC',
'new' => 'DESC',
'others_best_seller' => 'DESC',
'others_new' => 'DESC',
)
);
Ended up getting all the posts, created arrays for best seller, new, others, looped through each post and assigned to appropriate array, merged the arrays, then looped through the merged array to display the posts, works.
To do what you originally asked you need to use clauses for your meta_query. see ‘orderby’ with multiple ‘meta_key’s on this page https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters, it’s the 10th code snippet in the Order & Orderby Parameters section.
The topic ‘orderby multiple field values’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.