Having trouble setting user metadata on wordpress init hook - wordpress

I want to insert some user meta data to determine if a user has logged in before or not - with the intention of showing them a welcome screen if they havent.
I've google searched all these functions but they just don't seem to be working for me.
Here is my code...
add_action('init', function() {
$user_ID = get_current_user_id();
$has_visited = get_user_meta($userID, 'has_visited');
//check if has_visited key exists - if it doesn't, user's first visit
if(!$has_visited) {
//set the has_visited key
update_user_meta($user_ID, 'has_visited', 1);
echo 'user has not logged in before';
exit;
}
else { echo 'user has logged in before'; exit; }
});
Do these functions work on the init hook. I need them to so I can redirect the user to another page if it is their first visit.
Thanks in advance for your help and wisdom.

Because you have a typo here:
$has_visited = get_user_meta($userID, 'has_visited');
But, you sad this:
$user_ID = get_current_user_id();
So $user_ID and $userID is not the same.
Anyway, first you need to create another condition, to check, is the user logged in, because if not, then there will be no user ID.
So your complete code should be like this:
add_action('init', function() {
if (is_user_logged_in()) { //Added this
$user_ID = get_current_user_id();
$has_visited = get_user_meta($user_ID, 'has_visited', true); //Fixed this
//check if has_visited key exists - if it doesn't, user's first visit
if (!$has_visited) {
//set the has_visited key
update_user_meta($user_ID, 'has_visited', 1);
echo 'user has not logged in before';
exit;
} else {
echo 'user has logged in before';
exit;
}
}
echo "User not logged in";
});

Related

First time login redirect - amend code only for 'subscriber' user role

I'm using the code below to redirect users to a welcome page upon their first login. It works a treat, but I need to apply it to the 'subscriber' user role only.
add_action( 'user_register', 'myplugin_registration_save', 10, 1 );
function myplugin_registration_save( $user_id ) {
// insert meta that user not logged in first time
update_user_meta($user_id, 'prefix_first_login', '1');
}
// hook when user logs in
add_action('wp_login', 'your_function', 10, 2);
function your_function($user_login, $user) {
$user_id = $user->ID ;
// getting prev. saved meta
$first_login = get_user_meta($user_id, 'prefix_first_login', true);
// if first time login
if( $first_login == '1' ) {
// update meta after first login
update_user_meta($user_id, 'prefix_first_login', '0');
// redirect to given URL
wp_redirect( 'http://www.example-url.com' );
exit;
}
}
Bearing in mind I don't know anything, to me it seems like I need to add another 'if' element. I.e. If 'it's the user's first-time login' and 'the user has a subscriber role'. But I've no idea!
Please could someone help me amend this?

Show different message to logged in and non logged in users on particular post type wordpress

I have a question-answer plugin installed so the post type is example.com/question/
I want to show the message just below the post content
it should say "Login or Register" to non logged in users
and welcome to logged-in users
Try adding this code to your theme where applicable:
if (is_user_logged_in()) {
$current_user = wp_get_current_user();
echo 'Welcome ' . esc_html($current_user->display_name);
} else {
// Save current page url for redirect after login (optional):
global $wp;
$redirect = home_url($wp->request);
echo 'Login or Register';
}
Also: WordPress has a native function for that - wp_loginout():
https://developer.wordpress.org/reference/functions/wp_loginout/
It won't show the welcome message off the box, but will give logged in users the option to log out instead.
You're looking for is_user_logged_in();
Determines whether the current visitor is a logged in user.
Source # https://developer.wordpress.org/reference/functions/is_user_logged_in/
<?php
if ( 'question' === get_post_type() ) {
if ( ! is_user_logged_in() ) {
echo 'An account is required.';
} else {
// ...
};
};

Wordpress Automatic Login after Registration in Plugin

I have a plugin for registration process in wordpress. There was no password field but I created a password field and inserted the password instead of sending random password in emails. It is using wp_create_user function to create the user.
Now, I am trying to make the automatic login after registration but failed in it.
I tried the following function but failed in it. Please someone help.
wp_set_current_user($user_id); // set the current wp user
wp_set_auth_cookie($user_id); // start the cookie for the current registered user
wp_redirect(home_url());
Here is the process that I have been using, it's not complete but how I think that it must work.
$status = wp_create_user($username, $user_pass, $email);
$user_data = $wpdb->get_row("SELECT * FROM $users_table where user_login='$username' ");
$user_id = isset($user_data) ? $user_data->ID : 0;
if (is_wp_error($status)) {
$errors[] = language_code('USER_NAME_ALREADY_EXIST_PLEASE_TRY_ANOTHER_ONE');
} else {
wp_set_current_user($user_id);
wp_set_auth_cookie($user_id);
wp_redirect( home_url() );
}
Try following code into your theme functions.php file,It will work
function auto_login_new_user( $user_id ) {
wp_set_current_user($user_id);
wp_set_auth_cookie($user_id);
wp_redirect( home_url() );
exit;
}
add_action( 'user_register', 'auto_login_new_user' );

Autologin user after registration Wordpress

I am trying to autologin a user after registration.
I am trying this in functions.php file:
add_action( 'user_register', 'auto_login_user' );
function auto_login_user($user_id) {
$user = new WP_User($user_id);
$user_login_var = $user->user_login;
$user_email_var = stripslashes($user->user_email);
$user_pass_var = $user->user_pass;
$creds = array();
$creds['user_login'] = $user_login_var;
$creds['user_password'] = $user_pass_var;
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error($user) )
echo $user->get_error_message();
}
I am getting ERROR:
The password you entered for the username "TheNewUserCreated" is incorrect. Lost your password?
How Can I take the password from the User object?
Also because this is a custom registration process in template registration.php I tried to take it with $_POST and run the function in that file but I didnt have any success that way too...
EDIT:
Ok I am getting the encrypted password, so what is the solution here, how can I autologin the user? Maybe I can do this in registration.php page?
Add below function to functions.php file
function auto_login_new_user( $user_id ) {
wp_set_current_user($user_id);
wp_set_auth_cookie($user_id);
// You can change home_url() to the specific URL,such as
//wp_redirect( 'http://www.wpcoke.com' );
wp_redirect( home_url() );
exit;
}
add_action( 'user_register', 'auto_login_new_user' );
If you are using wp_insert_user(); to register your users then to auto-login them it's simple.
This function returns the user ID if success, so use it to login that user.
$id = wp_insert_user($data);
//so if the return is not an wp error object then continue with login
if(!is_wp_error($id)){
wp_set_current_user($id); // set the current wp user
wp_set_auth_cookie($id); // start the cookie for the current registered user
}
but to follow what you have already it can be like this:
add_action( 'user_register', 'auto_login_user' );
function auto_login_user($user_id) {
wp_set_current_user($user_id); // set the current wp user
wp_set_auth_cookie($user_id); // start the cookie for the current registered user
}
//this code is a bit tricky, if you are admin and you want to create a user then your admin session will be replaced with the new user you created :)
function auto_login() {
$getuserdata=get_user_by('login',$_GET['login']);
$tuserid=$getuserdata->ID;
$user_id = $tuserid;
$user = get_user_by( 'id', $user_id );
if( $user ) {
wp_set_current_user( $user_id, $user->user_login );
wp_set_auth_cookie( $user_id );
do_action( 'wp_login', $user->user_login );
}
}
add_action('init', 'auto_login');
i had have the same problem as your and found this best solution. try this in your functions.php file. and one thing more use submit your reset form in a function in functions.php file

Redirect user after first login in wordpress?

This code checks if a user is logging in for the first time, that is after registration. I want to redirect him to a custom page if so. Otherwise, redirect him to the homepage or admin page.
function mylogin_redirect() {
global $user_ID;
if( $user_ID ) {
$user_info = get_userdata( $user_ID );
// If user_registered date/time is less than 48hrs from now
// Message will show for 48hrs after registration
if ( strtotime( $user_info->user_registered ) > ( time() - 172800 ) ) {
header("Location: http://example.com/custompage");
} elseif( current_user_can( 'manage_options' )) {
header("Location: http://example.com/wp-admin/");
} else {
header("Location: http://example.com/");
}
}
}
add_action('wp_head', 'mylogin_redirect');
But it doesn't work? My guess is it doesn't get hooked into wp_head...
I tried the following using login_redirect filter:
function mylogin_redirect($redirect_to, $url_redirect_to = '', $user = null) {
global $user_ID;
if( $user_ID ) {
$user_info = get_userdata( $user_ID );
// If user_registered date/time is less than 48hrs from now
// Message will show for 48hrs after registration
if ( strtotime( $user_info->user_registered ) > ( time() - 172800 ) ) {
return get_bloginfo('url') . "/custompage/";
} elseif( current_user_can( 'manage_options' )) {
return admin_url();
} else {
return get_bloginfo('url');
}
}
}
add_filter('login_redirect', 'mylogin_redirect');
Though it logs me in, it doesn't get me anywhere but to http://example.com/wp-login.php instead with a blank page.
UPDATE:
Ok, I don't know what's happening. Using the filter hook, I can get to the intended destination only after second login. Well not really second login but on the second click of the login button. I did it like so: enter credentials -> login -> (wrong page) -> hit back button -> enter credentials again -> login -> (correct page). Weird.
You need to adjust your filter call like so;
// filter name, callback, priority, accepted args
add_filter('login_redirect', 'mylogin_redirect', 10, 3);
Redirecting users on first login in WordPress: Cookie-based solution & User meta table based solution

Resources