我有一个名为“book”的CPT,我想限制这本书的前端视图,就像特定角色用户只能view 这本书的内容来自前端,默认情况下任何人都可以看到来自前端的CPT帖子,我已经试过了capabilities 和map_meta_cap 但没有得到预期的结果。
CPT代码:
$args = array(
\'labels\' => $labels,
\'hierarchical\' => true,
\'description\' => \'test book\',
\'supports\' => array( \'title\', \'editor\', \'author\'),
\'public\' => true,
\'show_ui\' => true,
\'show_in_menu\' => true,
\'show_in_nav_menus\' => true,
\'publicly_queryable\' => true,
\'has_archive\' => true,
\'query_var\' => true,
\'rewrite\' => true,
\'capability_type\' => array(\'book\', \'books\'),
\'capabilities\' => array(
\'edit_post\' => \'edit_book\',
\'edit_posts\' => \'edit_books\',
\'edit_others_posts\' => \'edit_others_books\',
\'publish_posts\' => \'publish_books\',
\'read_post\' => \'read_book\',
\'read_private_posts\' => \'read_private_books\',
\'delete_post\' => \'delete_book\'
)
);
register_post_type( \'book\', $args );
功能:
// "lite_user" is a custom user role to manage book
$roles = array( get_role(\'lite_user\') );
foreach($roles as $role) {
if($role) {
$role->add_cap(\'read\');
$role->add_cap(\'edit_book\');
$role->add_cap(\'read_book\');
$role->add_cap(\'delete_book\');
$role->add_cap(\'edit_books\');
$role->add_cap(\'edit_others_books\');
$role->add_cap(\'publish_books\');
$role->add_cap(\'read_private_books\');
}
}
根据此代码,任何公众都可以从前端查看/访问这些书籍,但我想限制这一点,
lite_user 角色用户只能从前端查看/访问书籍。
最合适的回答,由SO网友:Pedro Coitinho 整理而成
您可以筛选the_content
要确保只有戴着合适帽子的人才能看到它,请执行以下操作:
function filter_the_content( $content ) {
// Check post type is book
// and that the current user is not lite user
if (get_post_type() == \'book\'
&& ! current_user_can( \'read_book\' ) ) {
// return a message in place of the content
return \'Why do you want to see this book? You can\\\'t read!\';
}
// otherwise, show content
return $content;
}
add_filter( \'the_content\', \'filter_the_content\' );
However! 这只适用于lite用户,这意味着任何其他用户(包括管理员)都无法从前端看到它。
您必须添加read_book
其他角色的能力。
希望这就是你要找的。