Home  >  Article  >  CMS Tutorial  >  How to restrict some WordPress user roles from entering the backend

How to restrict some WordPress user roles from entering the backend

藏色散人
藏色散人forward
2020-04-05 17:10:003003browse

How to restrict some WordPress user roles from entering the backend

Sometimes we want to restrict WordPress to some user roles from accessing the backend, which can be achieved through the following code.

1. Only administrator, editor and author roles are allowed to access the backend

Add the following code to the current theme function template functions.php:

add_action( 'init', 'zm_redirect_wp_admin' );
function zm_redirect_wp_admin() {
if ( is_admin() && is_user_logged_in() && !current_user_can( 'manage_options' ) && !current_user_can( 'publish_pages' ) && !current_user_can( 'publish_posts' ) && ( !defined( 'DOING_AJAX' ) || !DOING_AJAX )  ){
wp_safe_redirect( home_url() );
exit;
}
}

Determine whether to log in and User roles, user roles that are prohibited from accessing the backend will jump directly to the homepage of the website.

If you need to jump to a specified page link, such as the front-end user center, you can modify the code in line 4 to be similar:

wp_safe_redirect( 'https://zmingcx.com/' );

Can only jump to links within the site, not to Off-site links.

If only administrators are allowed to access the backend, you can delete the code that allows editors and authors to enter the backend:

&& !current_user_can('publish_pages') && !current_user_can('publish_posts')

2. Prohibit default registered user roles from entering the backend

The default registered user role refers to: WordPress backend → Settings → General, set the role in the default role for new users.

if ( is_admin() && ( !defined( 'DOING_AJAX' ) || !DOING_AJAX ) ) {
$current_user = wp_get_current_user();
if($current_user->roles[0] == get_option('default_role')) {
wp_safe_redirect( home_url() );
exit();
}
}

Code from: www.ludou.org

If you modify the default role for a new user, it will be invalid for users with other roles that have been registered before.

The above two pieces of code have added judgment and will not affect the front-end ajax request.

Related recommendations: "WordPress Tutorial"

The above is the detailed content of How to restrict some WordPress user roles from entering the backend. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:zmingcx.com. If there is any infringement, please contact admin@php.cn delete