Sort by ACF lname
April 3, 2025 · AI Conversations
User
$args = array(
'post_type' => 'contact',
'post_status' => 'publish',
'posts_per_page' => -1,
'order' => "ASC",
"orderby" => "title",
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'show_in_list', // Prüfen, ob show_in_list aktiv gesetzt ist
'value' => true,
'compare' => '==',
),
array(
'key' => 'show_in_list', // Wenn das Feld nicht vorhanden ist, gebe die Kontakte trotzdem aus
'compare' => 'NOT EXISTS',
)
),
);
sort by acf lname
'post_type' => 'contact',
'post_status' => 'publish',
'posts_per_page' => -1,
'order' => "ASC",
"orderby" => "title",
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'show_in_list', // Prüfen, ob show_in_list aktiv gesetzt ist
'value' => true,
'compare' => '==',
),
array(
'key' => 'show_in_list', // Wenn das Feld nicht vorhanden ist, gebe die Kontakte trotzdem aus
'compare' => 'NOT EXISTS',
)
),
);
sort by acf lname
Assistant
To sort the posts by an ACF field named `lname` (last name), you need to use the `meta_key` and `orderby` parameters in your query. Here's how you can modify your `$args` array to sort by the custom field `lname` instead of the post title:
$args = array(
'post_type' => 'contact',
'post_status' => 'publish',
'posts_per_page' => -1,
'order' => 'ASC',
'orderby' => 'meta_value',
'meta_key' => 'lname', // ACF field to sort by
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'show_in_list',
'value' => true,
'compare' => '==',
),
array(
'key' => 'show_in_list',
'compare' => 'NOT EXISTS',
)
),
);
### Notes:
– `meta_key` is used to specify which custom field you want to sort by.
– `orderby` is set to `meta_value` to sort based on the value of `lname`.
– If `lname` stores numbers and you want numeric sorting, use `meta_value_num` instead of `meta_value`.
Let me know if you need to sort by multiple fields (e.g., `lname`, then `fname`).