Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only administrator allow to access wp-admin and login?

Tags:

php

wordpress

I would like to do that only administrator(role) allow to login with wp-admin not any other role, other uses like(editor,author) are login from front end and it's working fine but i would like only administrator can login through wp-admin.

I have used ultimate member plug in for front end login. Ultimate Plugin link

also i have used below code for access wp-admin only for administrator(role) but it's not working.

<?php
function restrict_admin(){
//if not administrator, kill WordPress execution and provide a message
   if( !current_user_can('administrator') ) {
        wp_die( __('You are not allowed to access this part of the site') );
    }
}
add_action( 'admin_init', 'restrict_admin', 1 );
?>
like image 425
Samir Sheikh Avatar asked Sep 03 '25 16:09

Samir Sheikh


1 Answers

Thank you guys for your help, I am answering my own question hope this will help others too.

I have referred this link https://developer.wordpress.org/reference/functions/wp_authenticate/

I have solved this with hook wp_authenticate

 add_action( 'wp_authenticate' , 'check_custom_authentication' );
  function check_custom_authentication ( $username ) {

    $username;
     $user = new WP_User($username);
     $user_role_member=$user->roles[0];



    if($user_role_member == 'author' || $user_role_member == 'editor'){
        session_destroy();
        wp_redirect( home_url() );
        exit;
    }

 }
like image 186
Samir Sheikh Avatar answered Sep 05 '25 06:09

Samir Sheikh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!