WordPress theme code editing

How to automatically login a WordPress user in your PHP script

I was having some problems using the WordPress function wp_insert_post in a cron job I was working on, and I remembered having read somewhere that the wp_insert_post -function reacted differently depending on whether or not a user was logged in or not, so I found some code that automatically logged in a user, which I then added to the top of my PHP-script, and voila, the problem was solved:

<?php 
require('wp-blog-header.php'); 
$user_login = 'admin'; 
$user = get_userdatabylogin($user_login);
$user_id = $user->ID; 
wp_set_current_user($user_id, $user_login);
wp_set_auth_cookie($user_id); 
do_action('wp_login', $user_login); 
?>
How to automatically login a WordPress user in your PHP scriptClick To Tweet

Now, remember to set the proper path for the wp-blog-header.php file. (I know, there are other ways of loading the WordPress functions).

Secondly, remember to set the correct username. In this example I have used the default ‘admin’.

Notice how you do not need to enter the password for the user? This is powerful stuff, but be careful where you use it.

Error: Please enter a valid email address

Error: Invalid email

Error: Please enter your first name

Error: Please enter your last name

Error: Please enter a username

Error: Please enter a password

Error: Please confirm your password

Error: Password and password confirmation do not match