Amit

How to set up User email verification after Signup?

  1. First You’ve to create two user meta call activation_code and account_activated
// Add Extra User meta Fields
function ab_user_custom_userfields( $contactmethods ) {
 //Adds customer contact details
 $contactmethods['activation_code'] = 'Activation Code';
 $contactmethods['account_activated'] = 'Account Activated';
 return $contactmethods;
 }
add_filter('user_contactmethods','ab_user_custom_userfields',10,1);
  1. You’ve to copy and paste the following code to the theme functions file:

Theme Function File (function.php): You can locate this file in the Theme of the WordPress website. You can edit this file from the WordPress dashboard through Appearance > Theme Editor.

add_action( 'user_register', 'ab_user_email_verification', 10, 2 );
function ab_user_email_verification( $user_id ) {
    // get user data
    $user_info = get_userdata($user_id);
    // create md5 code to verify later
    $code = md5(time());
    // make it into a code to send it to user via email
    $string = array('id'=>$user_id, 'code'=>$code);
    // create the activation code and activation status
    update_user_meta($user_id, 'account_activated', 0);
    update_user_meta($user_id, 'activation_code', $code);
    // create the url
    $url = get_site_url(). '/my-account/?act=' .base64_encode( serialize($string));
    // basically we will edit here to make this nicer
    $html = 'Please click the following links <br/><br/> <a href="'.$url.'">'.$url.'</a>';
    // send an email out to user
    wp_mail( $user_info->user_email, __('Email Subject','text-domain') , $html);
}

You can check for $_GET[‘act’] and then activate if that’s a valid key by updating the meta value account_activated. You can use wp_authenticate_user hook to verify activation status every time when user tries to login.

add_action( 'init', 'verify_user_code' );
function verify_user_code(){
    if(isset($_GET['act'])){
        $data = unserialize(base64_decode($_GET['act']));
        $code = get_user_meta($data['id'], 'activation_code', true);
        // verify whether the code given is the same as ours
        if($code == $data['code']){
            // update the user meta
            update_user_meta($data['id'], 'account_activated', 1);
            wc_add_notice( __( '<strong>Success:</strong> Your account has been activated! ', 'text-domain' )  );
        }
    }
}

Last Update on:March 5th, 2023 at 5:19 pm


How to hide media uploads by other users in WordPress
Previous post