所以,我想拒绝用户访问wordpress仪表板的能力。但是,我想允许用户使用前端PM,它使用AJAX在用户之间发送消息。
如何允许PM但拒绝对仪表板的所有访问?
经典的functions.php方法:
add_action( 'init', 'my_custom_dashboard_access_handler');
function my_custom_dashboard_access_handler() {
// Check if the current page is an admin page
// && and ensure that this is not an ajax call
if ( is_admin() && !( defined( 'DOING_AJAX' ) && DOING_AJAX ) ){
//Get all capabilities of the current user
$user = get_userdata( get_current_user_id() );
$caps = ( is_object( $user) ) ? array_keys($user->allcaps) : array();
//All capabilities/roles listed here are not able to see the dashboard
$block_access_to = array('subscriber', 'contributor', 'my-custom-role', 'my-custom-capability');
if(array_intersect($block_access_to, $caps)) {
wp_redirect( home_url() );
exit;
}
}
}
不幸的是,这会从AJAX重定向......想法?
如果我使用用户角色编辑器...用户可以访问仪表板吗?
基本上,只允许管理员访问仪表板......而不限制AJAX。
答案 0 :(得分:0)
您可以使用
function sm_restrict_admin_with_redirect() {
if( defined('DOING_AJAX') && DOING_AJAX ) {
//Allow ajax calls
return;
}
if( ! current_user_can( "manage_options" ) ) {
//Redirect to main page if the user has no "manage_options" capability
wp_redirect( get_site_url() );
exit;
}
}
add_action( 'admin_init', 'sm_restrict_admin_with_redirect', 1 );