How to Assign Temporary Roles to Users in WordPress?

Table of Contents

Implementing custom roles that expire after a set time or condition is met

WordPress friends! 👋

I’m here to make your WordPress life a little easier. If you’ve ever wanted to temporarily upgrade or change a user’s role in WordPress (like giving someone Administrator access for just a few hours), this tutorial is exactly what you need.

I’ll guide you through the process step-by-step, using simple language and clear instructions. By the time you finish reading, you’ll know how to assign temporary roles to your WordPress users that automatically revert after a set time—no more manual tracking or extra work for you.

Let’s get started, shall we? 🚀


How to Create a New User in WordPress (Quick Guide)

Method 1: Using the WordPress Dashboard

  1. Go to Users > Add New in your WordPress admin panel.
  2. Fill in these fields:
    • Username: Enter a unique username.
    • Email: Add the user’s email address.
    • Password: Generate or set a strong password.
    • Role: Choose a role (e.g., Subscriber, Editor).
  3. Click Add New User to save.

Method 2: Using Code

For developers, you can create a user programmatically with the following PHP code:


function create_new_user() {
    $username = 'new_user'; // Change to your desired username.
    $email = 'new_user@example.com'; // Add the user's email.
    $password = 'secure_password'; // Set a strong password.

    if (!username_exists($username) && !email_exists($email)) {
        $user_id = wp_create_user($username, $password, $email);
        $user = new WP_User($user_id);
        $user->set_role('editor'); // Change 'editor' to the role you need.
        echo "User '{$username}' created successfully!";
    } else {
        echo "Username or email already exists.";
    }
}
add_action('init', 'create_new_user');
💡 Quick Tip: Replace placeholders ($username, $email, $password) in the code with real values. Use a role like 'subscriber' or 'administrator' as per your needs.

That’s it! Use the dashboard for simplicity or the code for automation. 😊

Why Do You Need Temporary Roles in WordPress?

Sometimes, you don’t want to give someone permanent access to a specific role, especially for high-level roles like Administrator. Temporary roles can be super useful when:

  • You need to let someone edit settings, posts, or pages for a short time.
  • You want to give a freelancer or temporary worker access without worrying about forgetting to remove it later.
  • You’re managing a growing team and need a simple system to control access automatically.

With this method, you won’t have to manually track who has access to what—and more importantly, you reduce the risk of leaving sensitive permissions open longer than necessary.


Step 1: Copy the Code Template

Here’s the code you’ll need. Don’t worry—it’s beginner-friendly, and I’ll explain everything as we go along.

You can add this code to your theme’s functions.php file or create a custom plugin (recommended for better management).


// Assign a Temporary Role
function grant_temporary_role($username, $new_role, $duration_in_minutes) {
    // Get the user by username
    $user = get_user_by('login', $username);

    if ($user) {
        // Backup the current role dynamically
        $original_role = $user->roles[0]; 

        // Assign the new role
        $user->set_role($new_role);

        // Save expiration time and original role in user meta
        $expiration_time = time() + ($duration_in_minutes * 60); // Convert minutes to seconds
        update_user_meta($user->ID, 'temporary_role_expiration', $expiration_time);
        update_user_meta($user->ID, 'original_role', $original_role);

        echo "User '{$username}' has been assigned the role '{$new_role}' for {$duration_in_minutes} minutes.";
    } else {
        echo "User '{$username}' does not exist.";
    }
}

// Revert Expired Roles
function revert_expired_roles() {
    // Get all users with a temporary role expiration
    $users = get_users(['meta_key' => 'temporary_role_expiration', 'meta_compare' => 'EXISTS']);

    foreach ($users as $user) {
        $expiration_time = get_user_meta($user->ID, 'temporary_role_expiration', true);

        // If expiration time has passed, revert to the original role
        if ($expiration_time && time() > $expiration_time) {
            $original_role = get_user_meta($user->ID, 'original_role', true);

            if ($original_role) {
                $user->set_role($original_role); // Restore original role
            }

            // Remove temporary metadata
            delete_user_meta($user->ID, 'temporary_role_expiration');
            delete_user_meta($user->ID, 'original_role');

            echo "User '{$user->user_login}' has been reverted to their original role '{$original_role}'.";
        }
    }
}

// Add Temporary Role (Replace with Your Values)
add_action('admin_init', function () {
    $username = 'REPLACE_WITH_USERNAME'; // Example: 'john_doe'
    $new_role = 'REPLACE_WITH_TEMP_ROLE'; // Example: 'administrator'
    $duration = REPLACE_WITH_DURATION; // Example: 60 (in minutes)

    grant_temporary_role($username, $new_role, $duration);
});

// Automatically Check for Expired Roles
add_action('init', 'revert_expired_roles');

Step 2: Replace Placeholder Values

Now, let’s customize this code for your needs.

  • REPLACE_WITH_USERNAME: Enter the username of the person you want to assign the temporary role to. Example: 'john_doe'.
  • REPLACE_WITH_TEMP_ROLE: Define the role you want to assign temporarily. Example: 'administrator', 'editor', etc.
  • REPLACE_WITH_DURATION: Set the time (in minutes) for the temporary role. Example: 60 for 1 hour.
💡 Quick Tip: Unsure of a user’s current role? Go to your WordPress admin panel > Users. Hover over the username to see their assigned role.

How It Works

  1. Assign Temporary Role: The grant_temporary_role() function changes the user’s role and saves their original role with an expiration time.
  2. Revert Automatically: The revert_expired_roles() function runs every time your website is loaded and reverts the user’s role if the time has expired.

Example Scenarios

Scenario 1: Temporarily Promote a User to Administrator for 1 Hour


add_action('admin_init', function () {
    grant_temporary_role('john_doe', 'administrator', 60);
});

Scenario 2: Assign Editor Role for 30 Minutes


add_action('admin_init', function () {
    grant_temporary_role('jane_smith', 'editor', 30);
});
🔑 Quick Tip: Avoid assigning Administrator roles unless absolutely necessary. For most tasks, Editor or Author roles work just fine.

FAQs

Q1: Can I assign temporary roles to multiple users at once?

A: Yes! You can loop through a list of usernames in the grant_temporary_role() function to assign roles to multiple users.

Q2: What happens if a user’s role doesn’t revert?

A: Double-check that the revert_expired_roles() function is hooked to init and running properly. It should revert automatically.

Q3: Is this code compatible with WooCommerce roles?

A: Absolutely! You can assign temporary WooCommerce roles like Customer or Shop Manager.

Q4: Can I set longer durations, like days or weeks?

A: Yes! Simply calculate the total minutes. For example, for 3 days, use 4320 (60 minutes × 24 hours × 3 days).

Q5: Can I use a plugin instead of custom code?

A: Yes! Plugins like User Role Editor offer similar features, but custom code gives you more control.

Conclusion

Congratulations! 🎉 You’ve learned how to assign temporary roles to your WordPress users and automatically revert them after a set time. This technique is a game-changer for managing permissions and keeping your site secure.

If you found this guide helpful, leave a comment below and let me know! 😊

Scroll to Top