2017-07-06 114 views
0

所以,我想拒絕用戶訪問wordpress儀表板的能力。但是,我想讓用戶使用前端PM,它使用AJAX在用戶之間發送消息。WordPress:拒絕用戶訪問儀表板但允許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

您可以使用

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); 
相關問題