How can I disable the password change option for specific user in Wordpress?
I have a user where I set a new password each week for multiple users. But some tried to change the password for this user. I don't want that - but only for this specific user profile. All the other users should be able toi change their password.
I have tried different plugins but none of them work.
Thanks a lot if you can help on this!
Add this in your function.php file
class Password_Reset_Removed
{
function __construct()
{
add_filter( 'show_password_fields', array( $this, 'disable' ) );
add_filter( 'allow_password_reset', array( $this, 'disable' ) );
}
function disable()
{
if ( is_admin() ) {
$userdata = wp_get_current_user();
$user = new WP_User($userdata->ID);
if ( !empty( $user->roles ) && is_array( $user->roles ) && $user->roles[0] == 'administrator' )
return true;
}
return false;
}
}
$pass_reset_removed = new Password_Reset_Removed();
We have just removed the fields to change password from the back-end of the WordPress. Now, some users will also try to reset the password using the Lost your password? form from the log-in page.
In order to prevent them from doing that, we will remove lost password link and disable the lost password form by adding below code
function remove_lost_your_password($text)
{
return str_replace( array('Lost your password?', 'Lost your password'), '', trim($text, '?') );
}
add_filter( 'gettext', 'remove_lost_your_password' );
function disable_reset_lost_password()
{
return false;
}
add_filter( 'allow_password_reset', 'disable_reset_lost_password');
Note - you can update userid - as per your requirements
Related
I am using below authenticate filter to check the user's role before logging them in and its working fine as per my expectations.
add_filter( 'authenticate', 'my_admin_checkk',1000, 2);
function my_admin_checkk( $user ) {
if ( !is_wp_error($user) ) {
if ( in_array( 'stappro_founder',$user->roles ) || in_array( 'stappro_investor',$user->roles ) ){
return new WP_Error( 'login_failed', __( "Only staff can use this login.", "mysite_domain" ) );
} else {
// allow the login
return $user;
}
} else {
return $user;
}
}
This is working fine as it is not allowing users to login having stappro_founder or stappro_investor roles. This is working fine.
But I have a front end login template and login form through which I am login with these custom roles but the thing is add_filter( 'authenticate' filter getting called here whenever I am trying to login.
I have used remove_filter( 'authenticate', 'my_admin_check',1000, 1); as well but it still gets calling. Please see my full code below.
if ( isset($_POST['action']) == 'log-in' ) {
# Submit the user login inputs
$user = wp_signon(
array(
'user_login' => $_POST['user-name'],
'user_password' => $_POST['password']
)
, false );
remove_filter( 'authenticate', 'my_admin_check',1000, 1);
if ( is_wp_error($user) ) {
echo $user->get_error_message();
} else {
# Redirect to account page after successful login.
if ( $user->ID ) {
wp_set_current_user( $user->ID, $user->name );
wp_set_auth_cookie( $user->ID, true, false );
wp_redirect( home_url('profile') );
}
}
}
Can someone guide me how can I Remove Authenticate Filter here ? How can I allow users to be logged in from front end and disallow them from wp-admin from here on.
Thanks
I'm coming across an issue when trying to register a second user account once someone registers as a customer via WooCommerce. I have added the following woocommerce_created_customer hook:
add_action('woocommerce_created_customer', function($customer_id)
{
if(isset($_POST['second_user_first_name']) && isset($_POST['second_user_last_name']))
{
$createSecondUserId = wp_create_user(strtolower($_POST['second_user_first_name'].'-'.$_POST['second_user_last_name']).'-'.$customer_id, wp_generate_password(), 'test#test.com');
if(is_wp_error($createSecondUserId))
{
$errors = $createSecondUserId->errors;
print_r($errors);
die();
}
}
});
However I get the following error when submitting a new WooCommerce registration:
Array ( [existing_user_login] => Array ( [0] => Sorry, that username already exists! ) )
It's strange as I'm setting a random username within the wp_create_user function, so the usernames should not clash. Has anyone got any ideas?
You can use username_exists() to determines that the given username exists.
add_action( 'woocommerce_created_customer', function($customer_id){
if( isset( $_POST['second_user_first_name'] ) && isset( $_POST['second_user_last_name'] ) ) {
if( !username_exists( strtolower( $_POST['second_user_first_name'].'-'.$_POST['second_user_last_name'] ).'-'.$customer_id ) ){
$createSecondUserId = wp_create_user( strtolower( $_POST['second_user_first_name'].'-'.$_POST['second_user_last_name'] ).'-'.$customer_id, wp_generate_password(), 'test#test.com' );
if(is_wp_error($createSecondUserId)){
$errors = $createSecondUserId->errors;
print_r($errors);
die();
}
}
}
});
If the username already exists you can create a new one by adding a progressive numeric suffix. In this way you will be sure that the username of the second account will always be unique.
Note that if you run multiple tests with your current code you need to
make sure you remove the user with the email address test#test.com
otherwise you will get an error: [existing_user_email] => Sorry, that email address is already used!.
add_action('woocommerce_created_customer', function( $customer_id ) {
if ( isset($_POST['second_user_first_name']) && isset($_POST['second_user_last_name']) ) {
// create the username based on the form data
$username = strtolower( $_POST['second_user_first_name'] . '-' . $_POST['second_user_last_name'] ) . '-' . $customer_id;
// if the username already exists it creates a unique one
if ( username_exists($username) ) {
$i = 0;
while ( username_exists($username) ) {
$username = $username . '-' . ++$i;
}
}
// create the second user
$createSecondUserId = wp_create_user( $username, wp_generate_password(), 'test#test.com' );
}
});
The code has been tested and works. Add it to your active theme's functions.php.
I am using add_action( 'after_setup_theme', 'custom_login' ); hook in one of my website for auto redirect user to his dashboard page.
Here is my code :---
function custom_login($username, $password='') {
$creds = array();
$creds['user_login'] = $username;
$creds['user_password'] = $password;
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error($user) ){
echo $user->get_error_message();
}
}
// run it before the headers and cookies are sent
add_action( 'after_setup_theme', 'custom_login' );
Its working fine on old version, But now I have upgrade wordpress version and its creating problem with nonce.
Are you sure you want to do this?
Everytime this error display on the screen when I do anything like update plugin, theme and permalinks.
When I comment this code then website working fine except auto redirect functionality.
Here is my website url :- https://www.linearrecruitment.co.uk/
Please help me where I do mistake.
That's a normal behaviour - nonce is a token used by Wordpress to check the validity of the form in order to prevent CSRF attacks.
A valid login form in Wordpress should have an hidden input field generated with wp_nonce_field:
wp_nonce_field('my_login_form');
Then in the login function the token is checked with the wp_verify_nonce function:
if (!isset($_POST['my_login_form']) || !wp_verify_nonce($_POST['_wpnonce'], 'my_login_form')) {
die('Invalid form');
}
What you're trying to do (auto login) is done wrong as add_action doesn't send any parameter for the after_setup_theme hook, so your username is probably empty. I don't know how this could possibly work before, maybe it managed to log in somehow with an empty username.
I suggest you to declare some globals vars for your username and password, as it seems to be static inputs:
global $username, $password;
$username = 'my_login';
$password = 'my_password';
And then on the beginning of your function import those globals with:
global $username, $password;
So what about the nonce?
On the last versions of Wordpress, the check_admin_referer have changed a bit, from:
function check_admin_referer( $action = -1, $query_arg = '_wpnonce' ) {
if ( -1 == $action )
_doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '3.2' );
$adminurl = strtolower(admin_url());
$referer = strtolower(wp_get_referer());
$result = isset($_REQUEST[$query_arg]) ? wp_verify_nonce($_REQUEST[$query_arg], $action) : false;
if ( !$result && !(-1 == $action && strpos($referer, $adminurl) === 0) ) {
wp_nonce_ays($action);
die();
}
do_action( 'check_admin_referer', $action, $result );
return $result;
}
To :
function check_admin_referer( $action = -1, $query_arg = '_wpnonce' ) {
if ( -1 == $action )
_doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '3.2' );
$adminurl = strtolower(admin_url());
$referer = strtolower(wp_get_referer());
$result = isset($_REQUEST[$query_arg]) ? wp_verify_nonce($_REQUEST[$query_arg], $action) : false;
do_action( 'check_admin_referer', $action, $result );
if ( ! $result && ! ( -1 == $action && strpos( $referer, $adminurl ) === 0 ) ) {
wp_nonce_ays( $action );
die();
}
return $result;
}
As you can see they moved the check_admin_referer hook - now we can change the value of $result before the wp_nonce_ays function (the one that display the message you try to get rid of) as been called.
That mean we could add the following hook in the theme functions.php in order to force the nonce validation:
add_action( 'check_admin_referer', array('custom_check_admin_referer' ) );
function custom_check_admin_referer() {
return 1;
}
That should work around your problem, but you must be aware that this could possibly be a security issue - you maybe want to do more test in that function before returning 1.
I'm wondering if it's possible that when you create a new user user-new.php you're being redirect to the user's profile instead of to users.php
I'm having some custom fields who only show up when you edit a user, so to make the workflow more easy I would like that the admin gets redirect to the user's profile so he can add those custom fields instantly.
wp_redirect is filterable, so you could hook in to redirect after a user was successfully added. I tested the following, might need a few tweaks but it does the trick:
add_filter( 'wp_redirect', 'wp_redirect_after_user_new', 1, 1 );
function wp_redirect_after_user_new( $location )
{
global $pagenow;
if( is_admin() && 'user-new.php' == $pagenow )
{
$user_details = get_user_by( 'email', $_REQUEST[ 'email' ] );
$user_id = $user_details->ID;
if( $location == 'users.php?update=add&id=' . $user_id )
return add_query_arg( array( 'user_id' => $user_id ), 'user-edit.php' );
}
return $location;
}
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