wp-content » themes » functions.php » Display a message to the targeted User or random user ID

Display a message to the targeted User or random user ID

Here is a short snippet that you can use to programmatically display messages, for example, coupon codes to random (or targeted) users.

We can either set the ID ourselves and store it in the $random_user_id variable

// Manually set the user ID
$random_user_id = 1;

Or for example, get random user IDs from the database:

// Get random user IDs from the database
$users = get_users(array(
    'orderby' => 'RAND()',
    'number' => 1, // number of users to retrieve
    'fields' => 'ID' // retrieve only the user IDs
));

$random_user_id = isset($users[0]) ? $users[0] : null;

💡 Note that if there are no users in the database, or if the number parameter is set to a value greater than the number of users in the database, the $random_user_id variable will be null.


Now that we have the user ID, we can display a special message to that user:

//get the current user as WP_User object
$currentUser = wp_get_current_user();

//check if current user is available with isset() and then check if it's our targeted (random) user
if(isset($currentUser->ID) && $currentUser->ID === $random_user_id){
	//current user ID is matching our random user's ID
	echo "Welcome to our website, here is a special discount code for you!";
}

wp_get_current_user() function returns the current user’s information, such as their username, email, and role, as an object.

Was this post helpful?

Leave a Comment

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.

Recommended