Automatic Admin Login for WordPress, A Really Bad Idea

Sometimes when you’re working with a local site, especially with existing data, and need to log in as a user and don’t want to mess with resetting the password (or there’s some weird SSO/MFA that’s getting in the way) you just want it to work.

Well, here you go. This snippet will automatically log you in to WordPress using the admin login. I don’t recommend using this anywhere near production or on a server that’s publicly available–for obvious reasons.

But anyway, here’s the bad idea:

<?php
/**
 * Force login as admin user on every request.
 */
function lol_bad_idea_force_admin_login(): void {
	wp_die( 'This is a really bad idea!' ); // Remove this, it's here to stop copy paste problems for people who don't read the code.
	// Check if user is not already logged in.
	if ( ! is_user_logged_in() ) {
		// Grab user object by login name.
		$user = get_user_by( 'login', 'admin' );
		if ( $user ) {
			// Set the current user to this admin account.
			wp_set_current_user( $user->ID );
			// Set the WordPress auth cookie.
			wp_set_auth_cookie( $user->ID );
		}
	}
}
add_action( 'init', 'lol_bad_idea_force_admin_login' );
Code language: PHP (php)

Other Posts Not Worth Reading

Hey, You!

Like this kind of garbage? Subscribe for more! I post like once a month or so, unless I found something interesting to write about.


Comments

Leave a Reply