Restricting page by user role

I’ll try to answer the question from beginning to end

so for example, when user with customer role wants to login to example.com/about page, they will be redirected to another page.

I want to do this in software, not with a plugin

Note that you can turn the snippet into a plugin by adding this to the top of the file:

<?php
/**
 * Plugin Name: ByWorlds plugin
 */

Plugins are just PHP files with a comment at the top, there’s not much more to them than that. People say having lots of plugins is slow for the same reason that carrying lots of things is difficult, it doesn’t mean things magically get faster if you put them in your theme, just like carrying a 100lb weight is just as hard wether it’s a single weight or lots of little ones.

and I found the code below, but it didn’t work, I think it’s valid for the admin panel.

What it’s doing is redirecting anybody who visits WP Admin who is not an administrator to yoursite.com/login.

Note that it uses current_user_can to detect if you’re an admin, but that function isn’t asking if you are an administrator, it’s asking can the current user do things an admin can do, so it’s not as reliable, especially when using lower level roles. There is a better way to test if a user has a role though.

How can I do the feature I said? I will be glad if you help

First, we need to run this on template_redirect., the init hook is way too early, WordPress hasn’t even looked at the URL, it has no idea which page you’re on.

So start with this:

function ByWorlds_redirects() : void {
    // redirection code
}
add_action( 'template_redirect', 'ByWorlds_redirects' );

Then inside the function, check if it’s WP Admin, we don’t need to redirect frontend pages if we’re on the backend so we’ll return early and stop the check:

// we only want to redirect on the frontend
if ( is_admin() ) {
    return;
}

Then we need to check the users role:

How to check if a user is in a specific role?

if ( ! is_user_logged_in() ) {
    // redirects for logged out users
}

$user = wp_get_current_user();
if ( in_array( 'author', (array) $user->roles ) ) {
    // The user has the "author" role, do redirects for authors
}

if ( in_array( 'editor', (array) $user->roles ) ) {
    // do redirects for editors
}

// etc...

A lot of people might suggest using current_user_can for this, but this would be a mistake.

Then inside that we check the page we’re on and redirect:

if ( is_page('about) ) {
    wp_safe_redirect( wp_login_page() );
    exit;

or if we wanted to redirect somewhere else:

if ( is_page('about) ) {
    wp_safe_redirect( site_url( '/author_about' ) );
    exit;

Put these all together and you should be able to redirect any page to any other page based on the users role

tech