最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

content restriction - How can i restrict a page to certain user roles?

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Sep 29, 2020 at 21:50 fuxia 107k38 gold badges255 silver badges459 bronze badges asked Sep 29, 2020 at 21:41 Hayder AllawiHayder Allawi 1
Add a comment  | 

1 Answer 1

Reset to default 0

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.

发布评论

评论列表(0)

  1. 暂无评论