Support

Account

Home Forums General Issues Querying users by custom field

Solving

Querying users by custom field

  • I have created a custom checkbox field that is assigned to users. I would like to know if there is a way to query for users that have a certain value on these fields using WP_User_Query.

    I realize that I can query for all users and then loop through them and only display the ones that have that value using get_field() but that seems a little inefficient if the user base grows.

  • Yes there is. ACF stores fields on user forms in the usermeta table.

    The difficulty is that checkbox fields are arrays stored as serialized data. In order to do a user query you would need to use the “LIKE” compare method in the meta_query for the user query.

    something like

    
    'meta_query' => array(
      array(
        'key' => 'my_field',
        'value' => 'my_value',
        'compare' => 'LIKE'
      )
    )
    

    if you’re looking for more than one value then you’d need to look for each value with and ‘AND’ or ‘OR’ for the relation value, depending on what you want returned.

    https://codex.wordpress.org/Class_Reference/WP_User_Query

  • Hello, i think this is related to this topic. I have this code and doesn’t work.
    If i use just one category is ok but i don’t know how to use more that one. Can someone helps me please?

    <?php
    $categories = array(8,9);
    
    $args = array(
    	'role__in' => 'subscriber',
    	'meta_query' => array(
    		array(
    			'key' => 'field_648831166ce8e',
    			'value' => $categories,
    			'compare' => 'LIKE',
    		),
    	),
    	'fields' => array('user_email'),
    );
    
    $subscribers = get_users($args);
    
    foreach ($subscribers as $subscriber) {
    	echo '<span>' . esc_html($subscriber->user_email) . '</span>';
    }
    ?>
Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Querying users by custom field’ is closed to new replies.