Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log in and set current user on Wordpress with PHP?

Tags:

php

wordpress

I'm developing a custom wordpress login/register. I've tried almost everything I've seen on the net, but nothing seems to work when trying to set the current user.

I've simplified the code in a script in order to make it more clear:

This has been copied from 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 the trace that looks like everything works as expected:

 WP_User Object ( [data] => stdClass Object ( [ID] => 8 [user_login] => email [user_pass] => **********************. [user_nicename] => email [user_email] => [email protected] [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 come back to the wp_site I'm not logged_ in. Any Ideas?

Thanks.

like image 429
Buendiadas Avatar asked Jun 11 '15 08:06

Buendiadas


1 Answers

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 );
}
like image 91
sarath Avatar answered Sep 25 '22 19:09

sarath