Home > CMS Tutorial > WordPress > body text

How to restrict some WordPress user roles from entering the backend

藏色散人
Release: 2020-04-05 17:10:00
forward
2992 people have browsed it

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;
}
}
Copy after login

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/' );
Copy after login

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')
Copy after login

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();
}
}
Copy after login

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!

Related labels:
source:zmingcx.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template