zwt
zwt

Reputation: 1

how to sort post by ACF Field type "user" using WP_Query

With use of the Advanced Custom Fields plugin, I created a custom field (type: user,format : array). I'm trying to sort post by user display_name.

Recording to ACF/wordpress documentations, this is the args array used: array( 'post_status' => 'publish', 'post_type' => 'the_post_type', 'orderby' => 'meta_value', 'meta_key' => 'users', 'order' => "ASC" ); In this case the result is a sorted posts by user "ID" instead of user "display_name". How can i get the posts list output sorted by "display_name".

Upvotes: 0

Views: 365

Answers (1)

M Fahad Aziz
M Fahad Aziz

Reputation: 61

To sort the posts by the user's display name instead of their ID when using the Advanced Custom Fields plugin with a user array field, you'll need to modify your query arguments. Since the user field in ACF saves user data as an array, you'll need to specify the sub-key display_name to sort by the user's display name. Please try this;

$args = array(
'post_status' => 'publish',
'post_type' => 'the_post_type',
'meta_query' => array(
    array(
        'key' => 'users',  // Your ACF field key
        'compare' => 'EXISTS',
    ),
),
'orderby' => 'meta_value', // Sort by meta value
'meta_key' => 'users_0_display_name', // Sub-key for display_name
'order' => 'ASC',
);
$the_query = new WP_Query($args);

Make sure to replace 'users_0_display_name' with the correct sub-key of the user's display name in your ACF field. This should sort the posts by the user's display name in ascending order.

Upvotes: 0

Related Questions