您可以使用get_terms
如果当前用户不是管理员,或者在这种特定情况下,如果用户没有您分配的角色,则通过钩子查找所有类别并通过ID或slug限制对它们的访问。
add_filter(\'get_terms\', \'restrict_categories\');
function restrict_categories($categories) {
$onPostPage = (strpos($_SERVER[\'PHP_SELF\'], \'post.php\') || strpos($_SERVER[\'PHP_SELF\'], \'post-new.php\')); // check if we are in the new/edit post page
// if (is_admin() && $onPostPage && !current_user_can(\'level_10\')) { // check for user capabilities - level_10 is admin
if (is_admin() && $onPostPage && themename_check_user_role( \'category_restricted\' )) { // check for user role
$size = count($categories);
for ($i = 0; $i < $size; $i++) {
// if ($categories[$i]->slug != \'category_slug\')
if ($categories[$i]->term_id != \'1\') // then restrict the categories by ID
unset($categories[$i]);
}
}
return $categories;
}
代码的学分为:
wptricks. 我只记得我不久前读到过这篇文章。
Later edit:
您可以尝试将角色传递给current_user_can()
函数,但不能保证它正常工作,相反,您可以使用下面的函数检查用户角色。
/**
* Checks if a particular user has a role.
* Returns true if a match was found.
*
* @param string $role Role name.
* @param int $user_id (Optional) The ID of a user. Defaults to the current user.
* @return bool
*/
function themename_check_user_role( $role, $user_id = null ) {
if ( is_numeric( $user_id ) )
$user = get_userdata( $user_id );
else
$user = wp_get_current_user();
if ( empty( $user ) )
return false;
return in_array( $role, (array) $user->roles );
}
// example use for the current user
if ( themename_check_user_role( \'customer\' )
_e( "You\'ve got access!", \'themename\' );
else
_e( "Sorry, you don\'t have access!", \'themename\' );
作为旁注,最好包括
add_role
主题/插件激活功能。