How to log in and install the current user in Wordpress using PHP?

I am developing a custom loginpress / register . I tried almost everything I saw on the network, but nothing works when trying to set the current user.

I simplified the code in the script to make it more understandable:

This is copied from the wp docs example:

https://codex.wordpress.org/Function_Reference/wp_set_current_user

<?php include_once($_SERVER['DOCUMENT_ROOT']."/wp-config.php"); include_once($_SERVER['DOCUMENT_ROOT']."/wp-includes/registration.php"); include_once($_SERVER['DOCUMENT_ROOT']."/wp-includes/user.php"); include_once ($_SERVER['DOCUMENT_ROOT']."/"."db_connect.php"); $user_id = 8; $user = get_user_by( 'id', $user_id ); if( $user ) { $curr_user= wp_set_current_user( $user_id, $user->user_login ); print_r($curr_user); // This trace is showed below. wp_set_auth_cookie( $user_id ); do_action( 'wp_login', $user->user_login ); } ?> 

Here I show a trace that looks as if everything is working as expected:

  WP_User Object ( [data] => stdClass Object ( [ID] => 8 [user_login] => email [user_pass] => **********************. [user_nicename] => email [user_email] => email@gmail.com [user_url] => [user_registered] => 2015-05-06 11:23:13 [user_activation_key] => [user_status] => 0 [display_name] => username ) [ID] => 8 [caps] => Array ( [subscriber] => 1 [bbp_participant] => 1 ) [cap_key] => wp_capabilities [roles] => Array ( [0] => subscriber [1] => bbp_participant ) [allcaps] => Array ( [read] => 1 [level_0] => 1 [spectate] => 1 [participate] => 1 [read_private_forums] => 1 [publish_topics] => 1 [edit_topics] => 1 [publish_replies] => 1 [edit_replies] => 1 [assign_topic_tags] => 1 [subscriber] => 1 [bbp_participant] => 1 ) [filter] => ) 

Anyway, when I get back to wp_site , I am not registered at . Any ideas?

Thanks.

+5
source share
1 answer

Try this code

 $user_id = 8; $user = get_user_by( 'id', $user_id ); if( $user ) { $curr_user= new WP_User( $user_id , $user->user_login ); // print_r($curr_user); // This trace is showed below. wp_set_auth_cookie( $user_id ); do_action( 'wp_login', $user->user_login ); } 
+6
source