我正在尝试使自定义帖子类型由一群人(即用户部门)而不是仅由作者编辑。我不想让他们编辑其他组(部门)的人创建的帖子。为了解决这个问题,我使用map_meta_cap
筛选以映射自定义功能。这实际上工作得很好。如果我这样检查:user_can( $user_id_of_who_is_editing, \'edit_post\', $post_id )
对于同一部门的用户,返回true。
现在,如果属于同一部门的非所有者用户出现以下错误:
不允许您编辑此帖子。
如果wordpress未检查current_user_can( \'edit_post\', $post_id )
, 如何检查以及如何绕过它?
映射元映射筛选器:
add_filter( \'map_meta_cap\', function( $caps, $cap, $user_id, $args ) {
global $dept_based_cap_post_types;
if( isset( $args[0] ) ){
$post = get_post( $args[0] );
if( isset( $post->post_type ) && in_array( $post->post_type, $dept_based_cap_post_types ) ){
$edit = "edit_$post->post_type";
$delete = "delete_$post->post_type";
$read = "read_$post->post_type";
$post_belongs_to_users_department = lu_post_under_users_dept( $user_id, $post->ID );
}
else {
return $caps;
}
}
else {
return $caps;
}
/* If editing, deleting, or reading a post, get the post and post type object. */
if ( $edit == $cap || $delete == $cap || $read == $cap ) {
$post_type = get_post_type_object( $post->post_type );
/* Set an empty array for the caps. */
$caps = array();
}
/* If editing a post, assign the required capability. */
if ( $edit == $cap ) {
if ( $post_belongs_to_users_department || ( $user_id == $post->post_author && \'draft\' == $post->post_status ) )
$caps[] = $post_type->cap->edit_posts;
else
$caps[] = $post_type->cap->edit_others_posts;
}
/* If deleting a post, assign the required capability. */
elseif ( $delete == $cap ) {
if ( $post_belongs_to_users_department || ( $user_id == $post->post_author && \'draft\' == $post->post_status ) )
$caps[] = $post_type->cap->delete_posts;
else
$caps[] = $post_type->cap->delete_others_posts;
}
/* If reading a private post, assign the required capability. */
elseif ( $read == $cap ) {
if ( \'private\' != $post->post_status )
$caps[] = \'read\';
elseif ( $post_belongs_to_users_department || ( $user_id == $post->post_author && \'draft\' == $post->post_status ) )
$caps[] = \'read\';
else
$caps[] = $post_type->cap->read_private_posts;
}
return $caps;
}, 10, 4 );
自定义职位类型注册代码:
$capabilities = array(
\'edit_post\' => \'edit_registration\',
\'read_post\' => \'read_registration\',
\'delete_post\' => \'delete_registration\',
\'delete_posts\' => \'delete_registrations\',
\'delete_others_posts\' => \'delete_others_registrations\',
\'edit_posts\' => \'edit_registrations\',
\'edit_others_posts\' => \'edit_others_registrations\',
\'publish_posts\' => \'publish_registrations\',
\'read_private_posts\' => \'read_private_registrations\'
);
$args = array(
\'labels\' => $labels,
\'public\' => false,
\'publicly_queryable\' => false,
\'show_ui\' => current_user_can( \'edit_programs\' ) ? \'edit.php?post_type=program\' : true,
\'query_var\' => false,
\'capabilities\' => $capabilities,
\'has_archive\' => false,
\'hierarchical\' => false,
\'menu_icon\' => \'dashicons-clipboard\',
\'supports\' => array( null ) // Array must contain a value to remove the default fields
);
register_post_type( \'registration\', $args );