Automatically Log in as Administrator with a Single Click

Automatically Log in as Administrator with a Single Click

If you're a WordPress developer or site administrator, you might often need to log in to your site quickly for testing or debugging. Manually entering your username and password can be time-consuming, especially during development. To simplify this process, I’m sharing a handy code snippet that allows you to log in as the first administrator user with just a single click.

How Does This Code Work?

This code snippet is designed to automatically log you in as the first administrator user on your WordPress site when you add ?dev=1 to your site’s URL. Here’s how it works:

  1. Check for the Query Parameter: The code listens for the ?dev=1 parameter in the URL. If it detects this parameter, it triggers the login process.
  2. Find the First Administrator: It queries the WordPress database to find the first user with the administrator role, ordered by their user ID.
  3. Log in Automatically: Once the administrator user is found, the code logs you in as that user and redirects you to the WordPress admin dashboard.
  4. Error Handling: If no administrator user is found, the code displays an error message using wp_die().

How to Use This Code

To use this code, simply copy and paste it into your theme’s functions.php file:

<?php

add_action('init', function () {

    if (isset($_GET['dev'])) {

        // Find the first administrator

        $admin_users = get_users([

            'role'    => 'administrator',

            'orderby' => 'ID',

            'order'   => 'ASC',

            'number'  => 1, // Get only the first admin

        ]);

        if (!empty($admin_users)) {

            $admin_user = $admin_users[0]; // Get the first admin user

            wp_set_auth_cookie($admin_user->ID); // Log in as the admin

            wp_redirect(admin_url()); // Redirect to admin dashboard

            exit;

        } else {

            wp_die('No administrator user found.');

        }

    }

});

?>

    

Once the code is added to your functions.php file, simply visit your site’s URL with ?dev=1 appended to it. For example:

https://yoursite.com/?dev=1

    

If everything is set up correctly, you’ll be automatically logged in as the first administrator user and redirected to the WordPress admin dashboard.

Important Notes

  • Security Warning: This code is intended for development or staging environments only. Do not use it on a live production site, as it can pose a significant security risk.
  • Remove After Use: Once you’re done testing, make sure to remove the code from your functions.php file to prevent unauthorized access.

Conclusion

This code snippet is a great time-saver for WordPress developers and administrators who frequently need to log in to their sites during development. However, always remember to use it responsibly and only in safe environments. Happy coding!