这是一个基本(未经测试)版本的代码,我认为可以解决您的问题:
<?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\' );
可以有其他方法来解决这个问题——可能只是其中之一。