我想知道如何限制某个页面仅显示给特定的用户角色&;还显示一条错误消息,指出如果用户角色为其他角色,则不允许用户查看此页面。
任何帮助都将不胜感激。
我想知道如何限制某个页面仅显示给特定的用户角色&;还显示一条错误消息,指出如果用户角色为其他角色,则不允许用户查看此页面。
任何帮助都将不胜感激。
这是一个基本(未经测试)版本的代码,我认为可以解决您的问题:
<?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\' );
可以有其他方法来解决这个问题——可能只是其中之一。