When a user registers, I need to assign a random but unique, 4-digit number as user meta data. The number will be static and not change: Not by the user himself or any user with a higher capability. This number/meta data would be needed to be displayed when a user visits a specific page (post type: Page).
1 Answer
You can use the hook user_register to modify user data upon registration. You can use the function add_user_meta to add custom data to a user. Example:
add_action('user_register', 'add_pin_number', 10, 1);
function add_pin_number($user_id)
{
add_user_meta( $user_id, 'pin_number', $random_number , true );
}
You can look for php function out there to help you creating the random unique number. One idea is to create the number based on the user ID which is already unique.
-
+1 Perfect answer. The only thing that would be missing to make it overly complete: Checking the length of the ID and prepending zeros for shorter IDs. And: Longer IDs would need handling as well. When a user registers and deletes his account again, you would miss out a number, etc. But that's the only flaw of that concept. Maybe just updating a single options entry with the currently highest number (just
++
the old value and save it as a new one upon registration) would be simpler.– kaiserFeb 28, 2014 at 23:16
[users] random meta
as search string that only searches a specific tag archive for example. And yes, it took me quite some time to figure out what you're trying to do.