0

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:

$wpdb->get_results(
    "
    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

2 Answers 2

0

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:

<?php
    $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);

1
  • 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.. Commented Sep 10, 2012 at 17:58
0

this is working for me

if ( metadata_exists( 'user', $user_id, $meta_key ) ) {
    print_r("Exists");
} else {
    print_r("Not Exists");
}
2

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.