Web Development & WordPress

New User Registration with image upload Facility : WordPress

Here I am sharing you template file and the related functions.php file code to register a wordpress user ( user role is Editor)

The template is doing the following to register a new wordpress user

  1. Upload image
  2. Send mail to Admin and Registered user both after successful registration
  3. Saving the profile or uploaded image in /wp-content/uploads/USER_ID
  4. Redirect to a url ( slug is used in the code) after successful registration

Template File

<?php
/* Template Name: Coach Registration */
get_header();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $errors = new WP_Error();
    $user_login = sanitize_user($_POST['user_login']);
    $user_email = sanitize_email($_POST['user_email']);
    $first_name = sanitize_text_field($_POST['first_name']);
    $last_name = sanitize_text_field($_POST['last_name']);
    $phone_number = sanitize_text_field($_POST['phone_number']);
    $referrer_name = sanitize_text_field($_POST['referrer_name']);
    $herbalife_id = sanitize_text_field($_POST['herbalife_id']);
    // Additional validation code here (if needed)

    // Check if an image was uploaded
    if (!empty($_FILES['profile_image']['name'])) {
        // Create a temporary filename for the uploaded image
        $temp_filename = wp_upload_dir()['path'] . '/' . $_FILES['profile_image']['name'];

        // Move the uploaded image to the temporary folder
        move_uploaded_file($_FILES['profile_image']['tmp_name'], $temp_filename);
    }

    if (count($errors->get_error_messages()) == 0) {
        $user_data = array(
            'user_login' => $user_login,
            'user_pass' => $_POST['pass1'],
            'user_email' => $user_email,
            'role' => 'editor', // Change this to the desired role
            'first_name' => $first_name,
            'last_name' => $last_name,
        );

        $user_id = wp_insert_user($user_data);

        if (!is_wp_error($user_id)) {
            // Update user meta for phone number, referrer name, and Herbalife ID
            update_user_meta($user_id, 'phone_number', $phone_number);
            update_user_meta($user_id, 'referrer_name', $referrer_name);
            update_user_meta($user_id, 'herbalife_id', $herbalife_id);

            // If an image was uploaded, associate it with the user
    if (!empty($temp_filename)) {
            // Get the path to the user's folder
            $user_folder_path = wp_upload_dir()['basedir'] . '/Coach/' . $user_id;

            // Create the user's folder if it doesn't exist
            if (!file_exists($user_folder_path)) {
                mkdir($user_folder_path, 0755, true);
            }

            // Move the temporary image to the user's folder
            $new_image_path = $user_folder_path . '/' . $_FILES['profile_image']['name'];
            $move_result = rename($temp_filename, $new_image_path);

            // Log $move_result to see if it's true or false
            error_log("Move Result: " . var_export($move_result, true));

            // Update user meta with the path to the profile image
            update_user_meta($user_id, 'profile_image', $new_image_path);
        }


            // Registration successful

            // Send email to admin
            $admin_email = get_option('admin_email');
            $admin_subject = 'New Coach Registration';
            $admin_message = 'A new coach has registered with the following details:' . "\n\n";
            $admin_message .= 'Username: ' . $user_login . "\n";
            $admin_message .= 'Email: ' . $user_email . "\n";
            $admin_message .= 'Referrer Name: ' . $referrer_name . "\n";
            $admin_message .= 'Herbalife Member ID: ' . $herbalife_id . "\n";

            wp_mail($admin_email, $admin_subject, $admin_message);

            // Send email to the registrant
            $registrant_subject = 'Your Coach Registration Details';
            $registrant_message = 'Thank you for registering as a coach.' . "\n\n";
            $registrant_message .= 'Username: ' . $user_login . "\n";
            $registrant_message .= 'Password: ' . $_POST['pass1'] . "\n";
            
            wp_mail($user_email, $registrant_subject, $registrant_message);

            // Registration successful
           
            echo '<script>
                    alert("Successfully Registered");
                  </script>';

            // Redirect after a delay
            echo '<script>
                    setTimeout(function(){
                        window.location.href = "' . home_url('/coachs-portal/') . '";
                    }, 500); // 500 milliseconds (0.5 seconds) delay before redirection
                  </script>';

            exit;
        }
    }
}
?>

 
<h2>Register as a Coach</h2>
<br />
 
<br />

<form id="register-form" action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" method="post" enctype="multipart/form-data">
    <p>
  <input type="text" name="first_name" value="<?php if (!empty($_POST['first_name'])) echo esc_attr($_POST['first_name']); ?>" required>
		 <label for="first_name">First Name</label>
    </p>
    
<p>
  <input type="text" name="last_name" value="<?php if (!empty($_POST['last_name'])) echo esc_attr($_POST['last_name']); ?>" required>
		  <label for="last_name">Last Name</label>
    </p>
    <p>
        
        <input type="email" name="user_email" value="<?php if (!empty($_POST['user_email'])) echo esc_attr($_POST['user_email']); ?>" required>
		<label for="user_email">Email</label>
    </p>
    <p>
       
        <input type="text" name="phone_number" value="<?php if (!empty($_POST['phone_number'])) echo esc_attr($_POST['phone_number']); ?>" required>
		 <label for="phone_number">Phone Number</label>
    </p>
	
	 <p>
       
        <input type="text" name="referrer_name" value="<?php if (!empty($_POST['referrer_name'])) echo esc_attr($_POST['referrer_name']); ?>" >
		 <label for="referrer_name">Referrer Name</label>
    </p>
	 <p>
        <input type="text" name="herbalife_id" value="<?php if (!empty($_POST['herbalife_id'])) echo esc_attr($_POST['herbalife_id']); ?>" >
		 <label for="herbalife_id">Herbalife  ID </label>
	</p>	
    <p>
       
        <input type="text" name="user_login" value="<?php if (!empty($_POST['user_login'])) echo esc_attr($_POST['user_login']); ?>" required>
		 <label for="user_login">Username</label>
    </p>
    <p>
      
        <input type="password" name="pass1" required>
		  <label for="pass1">Password</label>
    </p>
    <p style="margin-bottom: 40px;">
    
        <input type="password" name="pass2" required>
		    <label for="pass2">Confirm Password</label>
    </p>
	
	
   	 <p style="margin-bottom: 40px;">
	   <!-- File input for image upload -->
    <input type="file" name="profile_image" accept="image/*">
		 <label for="coach_img"> Add photo for Coach’s Card</label>
</p>

 
    <p style="margin-bottom: 30px !important;">
        <input type="submit" name="submit" value="Register">
    </p>
</form>
<?php

get_footer();
?>

Function.php code

add_action('wp_enqueue_scripts', 'wp_enqueue_media');
 
function add_profile_image_field($user) {
    ?>
    <h3><?php _e('Profile Image', 'your-text-domain'); ?></h3>
    <table class="form-table">
        <tr>
            <th><label for="profile_image"><?php _e('Image', 'your-text-domain'); ?></label></th>
            <td>
                <?php
                $profile_image_url = esc_attr(get_user_meta($user->ID, 'profile_image', true));
                $profile_image_url = str_replace($_SERVER['DOCUMENT_ROOT'], '', $profile_image_url);
                if($profile_image_url){ 
				?>
                <img src="<?php echo home_url($profile_image_url); ?>" width="150" height="150" style="max-width: 100%;height: auto;display: block;margin-bottom: 12px;" />
				<?php }?>
                <input type="text" name="profile_image" id="profile_image" value="<?php echo esc_url($profile_image_url); ?>" class="regular-text" />
                <p class="description"><?php _e('Enter the URL of the user\'s profile image.', 'your-text-domain'); ?></p>
            </td>
        </tr>
    </table>
    <?php
}
add_action('show_user_profile', 'add_profile_image_field');
add_action('edit_user_profile', 'add_profile_image_field');

// Save the custom field when the profile is updated
function save_profile_image_field($user_id) {
    if (current_user_can('edit_user', $user_id)) {
        $profile_image_url = sanitize_text_field($_POST['profile_image']);
        // You may want to validate the URL here to ensure it's a valid image URL.
        update_user_meta($user_id, 'profile_image', $profile_image_url);
    }
}
add_action('personal_options_update', 'save_profile_image_field');
add_action('edit_user_profile_update', 'save_profile_image_field');

If you have any issue feel free to do comments

Leave a comment