我想限制我的作者在特定的父类别(受限制并由我创建)中发布,并允许他们在父类别的子类别(由每个作者创建)中创建和发布
基本上, 作者1仅限于在类别A中发布。他将在A类中创建和发布 - >子类别1等 作者2限于在类别B中发布。他将在B类中创建和发布 - >子类别1等
我发现代码运行良好,但并不能完全符合我的要求。实际上,插件限制作者仅在他创建的类别中发布。这是我想要的,但是对于子类别以及将特定父类别分配给特定作者的内容。
class SW_Category_Restriction{
private $user_cats = NULL;
public function __construct(){
//Save author ID for category
add_action( 'create_category', array( &$this, 'save_category_author' ) );
//Set manage_categories cap for 'Author'
add_action( 'admin_init', array( &$this, 'add_author_cap_categories' ) );
//Remove manage_categories capfor 'Author'
register_deactivation_hook( __FILE__, array( &$this, 'remove_author_cap_categories' ) );
//Filter categorys in new-post, edit-post, edit-categories
add_action( 'admin_print_scripts-post-new.php', array( &$this, 'filter_post_page' ) );
add_action( 'admin_print_scripts-post.php', array( &$this, 'filter_post_page' ) );
add_action( 'admin_print_scripts-edit-tags.php', array( &$this, 'filter_post_page' ) );
//just show own posts
global $pagenow;
if ( $pagenow == 'edit.php' )
add_filter( 'pre_get_posts', array( &$this, 'filter_edit_page' ) );
}
public function save_category_author( $term_id ) {
$user_id = get_current_user_id();
add_term_meta( $term_id, 'author', $user_id );
}
public function get_user_cats( $user_id ) {
$args = [
'hide_empty' => false,
'meta_query' => [
[
'key' => 'author',
'value' => $user_id,
]
]
];
$terms = get_terms( 'category', $args );
$ids = '-1,';
foreach ($terms as $term ) {
$ids .= $term->term_id . ',';
}
$ids = substr($ids, 0, -1);
$this->user_cats = $ids;
}
public function add_author_cap_categories() {
$role = get_role( 'author' );
$role->add_cap( 'manage_categories' );
}
public function remove_author_cap_categories() {
$role = get_role( 'author' );
$role->remove_cap( 'manage_categories' );
}
public function exclusions( $exclusions ){
$exclusions .= " AND ( t.term_id IN ( $this->user_cats ) OR tt.taxonomy NOT IN ( 'category' ) )";
return $exclusions;
}
public function filter_post_page() {
//check post-type
$screen = get_current_screen();
if ( $screen->post_type != 'post' )
return;
//just Author and lower
if ( current_user_can('delete_others_posts') )
return;
$user_id = get_current_user_id();
$this->get_user_cats( $user_id );
if ( empty( $this->user_cats ) )
return;
add_filter( 'list_terms_exclusions', array( &$this, 'exclusions' ) );
}
public function filter_edit_page( $query ) {
if ( current_user_can('delete_others_posts') )
return;
$query->set( 'author', get_current_user_id() );
return $query;
}
}
new SW_Category_Restriction();