纯代码让wordpress贡献者可以看到后台媒体,发布文章时只能看到自己关联的文章、图片和文档

纯代码让wordpress贡献者可以看到后台媒体,发布文章时只能看到自己关联的文章、图片和文档

以下是实现WordPress贡献者角色只能查看自己上传的媒体文件和相关文章的完整代码方案:

这段代码需要添加到当前主题的functions.php文件中。

// 限制贡献者只能查看自己上传的媒体
function filter_media_by_author( $query ) {
    if ( current_user_can( 'contributor' ) ) {
        $query['author'] = get_current_user_id();
    }
    return $query;
}
add_filter( 'ajax_query_attachments_args', 'filter_media_by_author' );

// 限制贡献者只能编辑自己的文章
function restrict_contributor_posts( $wp_query ) {
    if ( is_admin() && current_user_can( 'contributor' ) ) {
        global $current_user;
        $wp_query->set( 'author', $current_user->ID );
    }
}
add_action( 'pre_get_posts', 'restrict_contributor_posts' );

// 允许贡献者上传媒体
function allow_contributor_uploads() {
    $contributor = get_role( 'contributor' );
    $contributor->add_cap( 'upload_files' );
}
add_action( 'admin_init', 'allow_contributor_uploads' );

它会实现三个功能:

1、让贡献者可以上传媒体文件

2、在媒体库中只能看到自己上传的文件 3) 在文章列表中只能看到自己创建的文章。