WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm using gravity forms for a sign-up form and I set up a hidden field that is automatically filled with a random string generated and passed to the form by

add_filter("gform_field_value_random_number", "generate_random_number");
function generate_random_number($value){
   $value =     substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"     ,5)), 0, 7);

This is to use as a unique coupon code/user.This field also appears in their user profile.

Up to here all is well. Where I'm having trouble is checking the database that no user already has that coupon code. At first, I wanted to use get_user_meta, but that only works for one user_id at a time. I need it to check ALL users. So the second thing I thought of was to do a wpdb query somewhat like this:

    SELECT meta_value
    FROM $wpdb->usermeta
    WHERE meta_key = 'Referral'

My final function would basically be the following:

  1. Generate random number and return the variable with it (ex: $value)
  2. Do a while loop to check if $value already exists in the database
  3. End loop when $value does not match anything in the database.

I'm not sure how to make this happen. If anyone can give me a hand or point me in the right direction if this is wrong, it'd be much appreciated! :)

edit: Sorry, here's the site: http://colorplan.ca

share|improve this question

I personally try to stay away from mysql queries when I can use WordPress functions to achieve the same thing. You could try using get_users, Is this what you are trying to achieve:

    $blogusers = get_users('meta_value=Referral');
    foreach ($blogusers as $user) {
        echo $user->user_email;

Untested. But that should display every user with a null value for the user meta Refferal. If that works you could change echo $user->user_email;, to update_user_meta($user->id, 'Referral', $coupon_code);

share|improve this answer
Not sure I understand... Using get_users (which I didn't know about, thanks!), WP would need to return an array of all the users where the value for meta_key=Referral is not empty (which should never be the case) and then check that the randomly generated number is not equal to any of those in the array.. – Andrei Iancu Sep 10 '12 at 17:58

Your Answer


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.