纯代码让wordpress作者发布文章时只能看到自己关联的文章和图片

以下是实现WordPress作者只能看到自己关联的文章和图片的完整代码方案:

方法一:限制作者只能看到自己的文章和媒体文件

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

// 限制作者只能看到自己的文章
function posts_for_current_author($query) {
    global $pagenow;
    
    if ('edit.php' != $pagenow || !$query->is_admin)
        return $query;

    if (!current_user_can('edit_others_posts')) {
        global $user_ID;
        $query->set('author', $user_ID);
    }
    return $query;
}
add_filter('pre_get_posts', 'posts_for_current_author');

// 限制作者只能看到自己的媒体文件
function filter_media_by_author($query) {
    if (!current_user_can('edit_others_posts')) {
        global $current_user;
        $query['author'] = $current_user->ID;
    }
    return $query;
}
add_filter('ajax_query_attachments_args', 'filter_media_by_author');

第一部分限制作者在文章列表只能看到自己的文章,第二部分限制作者在媒体库只能看到自己上传的图片。代码会检查用户权限,如果不是管理员或编辑,则只显示当前用户的内容。

方法二: 限制作者只能看到自己的文章和完全限制访问他人的媒体

// 1. 限制作者只能看到自己的文章
function restrict_posts_to_author($wp_query) {
    if (is_admin() && !current_user_can('edit_others_posts')) {
        $wp_query->set('author', get_current_user_id());
    }
}
add_action('pre_get_posts', 'restrict_posts_to_author');

// 2. 完全限制媒体库访问
function restrict_media_library($query) {
    if (!current_user_can('edit_others_posts')) {
        $user_id = get_current_user_id();
        $query['author'] = $user_id;
        
        // 防止通过URL直接访问
        if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'query-attachments') {
            $query['author'] = $user_id;
        }
    }
    return $query;
}
add_filter('ajax_query_attachments_args', 'restrict_media_library');

// 3. 防止通过URL直接访问他人媒体
function check_attachment_access() {
    if (is_admin() && isset($_GET['post']) && $_GET['post']) {
        $post = get_post($_GET['post']);
        if ($post && $post->post_type == 'attachment' && 
            !current_user_can('edit_others_posts') && 
            $post->post_author != get_current_user_id()) {
            wp_die(__('您无权访问此文件'));
        }
    }
}
add_action('admin_init', 'check_attachment_access');