Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I want to associate certain users by means of a custom key stored in the user_meta for both users. There may be more than one-one relationships, so it'll be in an array. If 2 users have the same key in this _mm_group_membership array, they're part of the group.

Now since meta_value queries are restricted to simple comparisons (=, <, >, etc.) here's what I'm proposing, searching for users related to $user_id on the basis of group membership $key:

function linked_users_array ($user_id, $key) {
    $group = '_mm_group_membership';
    $users = get_users('meta_key='.$group.'&fields=all_with_meta');
    $linked_user_ids = array();
    foreach ($users as $u) {
        if (in_array($key, $u->$group)) {
            $linked_user_ids[] = $u->ID;
        }
    }
    return $linked_user_ids;
}    

2 questions on this:

1) Is $u->$group possible? Or do I need to use something along the lines of var_dump( $u->get( $group ) );?

2) I want to minimise hitting the database, so I don't really want an extra get_user_meta() call on each user in the loop. Is this possible?

Thanks in advance.

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

First of all, I believe your syntax is incorrect. Should be:

$group = '_mm_group_membership'; // key should be a string

Secondly, did you try using $u->get? Here's what the doc says:

If fields is set to all_with_meta, it will return an array of WP_User objects.

So yes, if you specified this parameter you should get a bunch of WP_User objects back. And yes, there should be a getter in the WP_User object, but you'd need to feed it that same $group variable to get the value for your key.

if($u->has_prop( $group )) {
    $meta_val = $u->get( $group );
}

Then you work with your value, which, as you mentioned, should be an array (of groups the user is in?). You might need to unserialize it, since WordPress tends to keep things as strings in the database.

share|improve this answer
    
Thanks. Fixed the typo. Excellent. I wanted to operate on the returned object, without any get_user_meta() calls. –  Freney Apr 11 '13 at 2:13
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.