How can i restrict a page to certain user roles?

I would like to know how can i restrict a certain page to be shown only to specific user roles also show an error message that the user is not allowed to view this page if the user role is otherwise.

Any help will be appreciated.

Topic content-restriction Wordpress

Category Web


This is a rudimentary (untested) version of the code that I can think will resolve your issue:

<?php
/**
 * Redirect UnAuthorized Users from my page.
 * 
 * Users will be redirected to another page if not authorized.
 */
function wpse375662_redirect_unauth_users() {
    // Not that particular page - bail out.
    if ( ! is_page( $page_id ) ) {
        return;
    }

    // User has permission - bail out.
    if ( current_user_can( $user_role_here ) ) {
        return;
    }

    // Add URL parameter.
    $parameterized_url = add_query_arg( $your_custom_page_url, 'unauth', true );

    // Redirect the user.
    wp_redirect( $parameterized_url, 302 );
    exit();
}

add_action( 'template_redirect', 'wpse375662_redirect_unauth_users' );

/**
 * Display a message upon redirection.
 */
function wpse375662_message_for_unauth_users() {
      if ( filter_input( INPUT_GET, 'unauth', FILTER_VALIDATE_BOOLEAN ) ) {
            echo '<div style="style="absolute; top: 300px; left: 50%; transform: translateX(-50%); z-index: 9999; padding: 2rem;" role="alert">You are not authorized to display the content of that page</div>';
      }
}

add_action( 'wp_footer', 'wpse375662_message_for_unauth_users' );

There could be other ways to tackle the issue - it could just be one of them.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.