send an email notification to the admin each time the website reach 100 more users

Home » Snippets » send an email notification to the admin each time the website reach 100 more users
0

Created with:

Visibility: 

public

Creator: Alex

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php
function wpturbo_send_user_notification() {
    // Check if the user count option is already set
    if (!get_option('wpturbo_user_count')) {
        // Get the total number of existing users
        $existing_user_count = count_users();
        $total_user_count = $existing_user_count['total_users'];

        // Set the initial user count option
        update_option('wpturbo_user_count', $total_user_count);
    }

    // Get the current user count from the option. Only count admin if not defined
    $current_user_count = get_option('wpturbo_user_count', 1);

    // Increment the user count by 1
    $new_user_count = $current_user_count + 1;

    // Check if the new user count is a multiple of 100
    if ($new_user_count % 100 === 0) {
        $admin_email = get_option('admin_email');
        $subject = 'Website User Milestone Reached';
        $message = 'Congratulations! Your website has reached a milestone of ' . $new_user_count . ' users. Keep up the good work!';
        wp_mail($admin_email, $subject, $message);
    }

    // Update the user count option
    update_option('wpturbo_user_count', $new_user_count);
}

add_action('user_register', 'wpturbo_send_user_notification');
				

Explanation:

In this updated code, we have added a check to see if the wpturbo_user_count option is already set. If the option is not set, it means that the function is being run for the first time, so we can count the existing users and set the initial user count option.

Inside the wpturbo_send_user_notification() function, we check if the option is set using the get_option() function and the ! (not) operator. If the option is not set, we proceed with counting the total number of existing users using the count_users() function and store it in the $total_user_count variable. Then, we set the initial user count option using the update_option() function.

After that, we retrieve the current user count from the option using the get_option() function and store it in the $current_user_count variable. We increment the user count by 1 to get the new user count.

Then, we check if the new user count is a multiple of 100, just as before, and send the email notification if it is.

Finally, we update the wpturbo_user_count option with the new user count using the update_option() function.

By adding this check, we ensure that the user count is only counted and the initial user count option is set once, preventing unnecessary counting on subsequent function calls.

Register an account to save your snippets or go Pro to get more features.