0

I'm attempting to use get_users to select users with only a certain meta value. In this case the meta key is extraInfo but the the values are in a serialized array. Can I pull users out like this? This is what I've been trying with no luck:

$meta_key = 'extraInfo[zip]';
$meta_value = $zip;
$query    = get_users('meta_key='.$meta_key.'&meta_value='.$meta_value);
4
  • There's no way to do this without writing the SQL yourself. You're better off saving data in individual keys if you need to query on it, much more efficient.
    – Milo
    Commented Feb 24, 2015 at 14:49
  • I agree. I'll need to make this update on almost 7000 users. Commented Feb 24, 2015 at 15:05
  • 1
    I suggest writing a script to get users, load their meta, then save it out to individual keys. You can use offset and number arguments to do it in batches so you don't crush your server.
    – Milo
    Commented Feb 24, 2015 at 17:18
  • Thanks. Thats exactly what I need to do. I'll post my solution when I have a working script. I've seen the same thing accomplished here on Stack Exchange but with custom post types. It will be similar. Commented Feb 24, 2015 at 18:06

2 Answers 2

1

The answer is, this can't be done with any efficiency. The best thing to do is pull the data out of the serialized array and save each as their own key/value pair in the wp_usermeta table. My key was extraInfo and the values I needed were serialized in the value. This is the script I've used to create new keys and values from the data automatically. The echoing was just used for some on screen feedback and isn't necessary. If you have a lot of users, you might want to use number and offest in the get_users query. Hope this helps someone.

<?php

$users = get_users( 'number=10' );
foreach ( $users as $user ) {
    $extras = unserialize(get_the_author_meta( "extraInfo", $user->ID ));
    foreach ($extras as $key=> $value) {
        echo '<p>' . $key . ': ' . $value . '</p>';
        update_user_meta( $user->ID, $key, $value);
    }
    echo '<p>' . esc_html( $user->user_email ) . '</p>';
    echo '<hr>';
}

?>
0
            <?php
            /**
             * are you sure that your meta value is ok
             */
            $meta_key = 'extraInfo[zip]';
            $meta_value = $zip;
            $query    = get_users(
            array(
                'meta_key' => $meta_key,
                'meta_value' => $meta_value
            ));
1
  • Yes I'm sure the value is good. It's definitely an issue with the meta values being serialized. Not sure there is way to get them without updating the whole save routine and pulling them out of the serialized array. Commented Feb 24, 2015 at 14:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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