自定义文章类型的功能
register_post_type()
函数接受一个$capabilities
数组作为其中一个(可选)参数。
它可能看起来像这样:
$capabilities = array(
'publish_posts' => 'publish_ypts',
'edit_posts' => 'edit_ypts',
'edit_others_posts' => 'edit_others_ypts',
'delete_posts' => 'delete_ypts',
'delete_others_posts' => 'delete_others_ypts',
'read_private_posts' => 'read_private_ypts',
'edit_post' => 'edit_ypt',
'delete_post' => 'delete_ypt',
'read_post' => 'read_ypt'
);
"ypt" 代表 "您的文章类型"。
之后,您可以为 WordPress 添加一个新角色,该角色具有这些确切的功能(可能还包括一些标准 WordPress 功能):
add_role(
'ypt_author',
'Author of your post type',
array(
'publish_ypts' => true,
'edit_ypts' => true,
'edit_others_ypts' => true,
'delete_ypts' => true,
'delete_others_ypts' => true,
'read_private_ypts' => true,
'edit_ypt' => true,
'delete_ypt' => true,
'read_ypt' => true,
// more standard capabilities here
)
);
使用插件可以实现后者,例如,查看Justin Tadlock的Members插件。
详细示例
为了给您提供更具体的示例:
add_action('init', 'ypt_register');
function ypt_register()
{
$labels = array(
'name' => _x('YPTs', 'post type general name'),
'singular_name' => _x('YPT', 'post type singular name'),
'add_new' => _x('Add New YPT', 'Team item'),
'add_new_item' => __('Add a new post of type YPT'),
'edit_item' => __('Edit YPT'),
'new_item' => __('New YPT'),
'view_item' => __('View YPT'),
'search_items' => __('Search YPTs'),
'not_found' => __('No YPTs found'),
'not_found_in_trash' => __('No YPTs currently trashed'),
'parent_item_colon' => ''
);
$capabilities = array(
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'rewrite' => true,
'capability_type' => 'ypt',
'capabilities' => $capabilities,
'hierarchical' => false,
'menu_position' => null,
'supports' => array( 'title', 'author', 'thumbnail' )
);
register_post_type( 'ypt' , $args );
flush_rewrite_rules( false );
}
add_filter( 'map_meta_cap', 'ypt_map_meta_cap', 10, 4 );
function ypt_map_meta_cap( $caps, $cap, $user_id, $args )
{
if ( 'edit_ypt' == $cap || 'delete_ypt' == $cap || 'read_ypt' == $cap ) {
$post = get_post( $args[0] );
$post_type = get_post_type_object( $post->post_type );
$caps = array();
}
if ( 'edit_ypt' == $cap ) {
if ( $user_id == $post->post_author )
$caps[] = $post_type->cap->edit_posts;
else
$caps[] = $post_type->cap->edit_others_posts;
}
elseif ( 'delete_ypt' == $cap ) {
if ( $user_id == $post->post_author )
$caps[] = $post_type->cap->delete_posts;
else
$caps[] = $post_type->cap->delete_others_posts;
}
elseif ( 'read_ypt' == $cap ) {
if ( 'private' != $post->post_status )
$caps[] = 'read';
elseif ( $user_id == $post->post_author )
$caps[] = 'read';
else
$caps[] = $post_type->cap->read_private_posts;
}
return $caps;
}
$capabilities
数组是你放入register_post_type()
函数中的参数之一。在其中,你将新的能力映射到常规文章的等效能力上。如果使用register_post_type()
而没有使用此可选参数,则适用常规能力。如果使用了它,则 pubish_posts 能力不包括您的文章类型 - 作者必须具有 publish_ypt 能力。 - Johannes Pille'hierarchical'
需要设置为true。否则,我的示例同样适用于您的字典条目。 - Johannes Pille'capability_type' => 'dictionary_entry',
它仍然不起作用,但我认为可能还有其他我遗漏的东西。 - emersonthis