Home › Forums › General Issues › Sort order of several ACF Fields
I’m trying to sort on several field’s values. The two fields I would like to sort: builder_lot & builder_title.
It is working for the first one but need help understanding how to add the second sort option.
$builder_args = array(
‘post_type’ => ‘builders’,
‘posts_per_page’ => -1,
‘meta_key’ => ‘builder_lot’,
‘orderby’ => ‘meta_value’,
‘order’ => ‘ASC’
);
$builder_query = new WP_Query( $builder_args );
if ( $builder_query->have_posts() ) {
while ( $builder_query->have_posts() ) {
echo $builder_lot.’ – ‘.builder_title;
} // end while
} // end if
example:
builder_lots values like 4, 55, 60, etc.
builder_title values like ‘Builder Name 1’, ‘Builder Name 2’, ‘Builder Name 3’, etc.
Looking to sort both ASC with builder_lot first, then by builder_title.
Output:
40 – Builder Name 1
40 – Builder Name 2
40 – Builder Name 3
55 – Builder Name 1
55 – Builder Name 2
55 – Builder Name 3
60 – Builder Name 1
60 – Builder Name 2
60 – Builder Name 3
Thanks!
You have to use a meta query with multiple values and clauses.
See the example of using clauses on the documentation for WP_Query() Order & Orderby Parameters. The example is titled “‘orderby’ with multiple ‘meta_key’s” and is currently the 10th example given.
Note, in your case you would use “EXISTS” for the compare setting on both meta keys.
I guess I’m missing something as this now returns nothing:
$builder_args = array(
'post_type' => 'builders',
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'AND',
'lot_clause' => array(
'key' => 'builder_lot',
'value' => 'meta_value',
'compare' => 'EXISTS',
),
'title_clause' => array(
'key' => 'builder_title',
'value' => 'meta_value',
'compare' => 'EXISTS',
),
),
'orderby' => array(
'lot_clause' => 'ASC',
'title_clause' => 'ASC',
),
);
I’m not sure if key=value parts of the clauses are correct.
The link you provided says: “Note that a ‘meta_key=keyname‘ must also be present in the query.”
you don’t need 'value' => ''
for either field and that could be causing the issue.
You must be logged in to reply to this topic.
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.