Methods to restrict some WordPress user roles from entering the background
Editor to share with you how to restrict some WordPress user roles from entering the background. I hope you will gain a lot after reading this article. Let's discuss it together.
Sometimes we want to restrict the access of some WordPress user roles to the background, which can be achieved through the following code.
Only administrator, editor and author roles are allowed to access the background
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 the user role, and prohibit the user role from accessing the background to jump directly to the home page of the site.
If you need to jump to the specified page link, such as the front-end user center, you can change the code on line 4 to look like this:
Wp_safe_redirect ('https://zmingcx.com/')
You can only jump to on-site links, not off-site links.
If only administrators are allowed to access the background, delete the code that allows editors and authors to enter the background:
& &! current_user_can ('publish_pages') & &! current_user_can (' publish_posts')
Second, prohibit the default registered user role from entering the background
The default registered user role refers to: the WordPress background → sets the → general, and sets the role in the default role of the new user.
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 ();}}
The code is from: www.ludou.org
If you modify the default role of a new user, it will not be valid for users of other previously registered roles.
The judgment is added to the above two pieces of code, which will not affect the front-end ajax request.
After reading this article, I believe you have a certain understanding of the methods of restricting some WordPress user roles to enter the background. If you want to know more about it, welcome to follow the industry information channel. Thank you for your reading!