WordPress 媒體庫隻顯示用戶自己上傳的文件

《WordPress 限制不同用戶角色可上傳的文件類型及大小》已經詳細介紹瞭用戶上傳的問題,今天分享下在 WordPress 媒體庫隻顯示用戶自己上傳的文件 的方法。在當前主題的 functions.php 文件添加下面的代碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
 * WordPress 媒體庫隻顯示用戶自己上傳的文件
 * https://www.wpdaxue.com/view-user-own-media-only.html
 */
//在文章編輯頁面的[添加媒體]隻顯示用戶自己上傳的文件
function my_upload_media( $wp_query_obj ) {
	global $current_user, $pagenow;
	if( !is_a( $current_user, 'WP_User') )
		return;
	if( 'admin-ajax.php' != $pagenow || $_REQUEST['action'] != 'query-attachments' )
		return;
	if( !current_user_can( 'manage_options' ) && !current_user_can('manage_media_library') )
		$wp_query_obj->set('author', $current_user->ID );
	return;
}
add_action('pre_get_posts','my_upload_media');
 
//在[媒體庫]隻顯示用戶上傳的文件
function my_media_library( $wp_query ) {
    if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/upload.php' ) !== false ) {
        if ( !current_user_can( 'manage_options' ) && !current_user_can( 'manage_media_library' ) ) {
            global $current_user;
            $wp_query->set( 'author', $current_user->id );
        }
    }
}
add_filter('parse_query', 'my_media_library' );

/**
* WordPress 媒體庫隻顯示用戶自己上傳的文件
* https://www.wpdaxue.com/view-user-own-media-only.html
*/
//在文章編輯頁面的[添加媒體]隻顯示用戶自己上傳的文件
function my_upload_media( $wp_query_obj ) {
global $current_user, $pagenow;
if( !is_a( $current_user, ‘WP_User’) )
return;
if( ‘admin-ajax.php’ != $pagenow || $_REQUEST[‘action’] != ‘query-attachments’ )
return;
if( !current_user_can( ‘manage_options’ ) && !current_user_can(‘manage_media_library’) )
$wp_query_obj->set(‘author’, $current_user->ID );
return;
}
add_action(‘pre_get_posts’,’my_upload_media’); //在[媒體庫]隻顯示用戶上傳的文件
function my_media_library( $wp_query ) {
if ( strpos( $_SERVER[ ‘REQUEST_URI’ ], ‘/wp-admin/upload.php’ ) !== false ) {
if ( !current_user_can( ‘manage_options’ ) && !current_user_can( ‘manage_media_library’ ) ) {
global $current_user;
$wp_query->set( ‘author’, $current_user->id );
}
}
}
add_filter(‘parse_query’, ‘my_media_library’ );

最終效果:非管理員用戶 在文章編輯頁面的[添加媒體]窗口(下圖1) 和 多媒體 管理界面(下圖2)隻顯示自己上傳的文件(還不能修正媒體數量顯示)

view-user-own-media-only-wpdaxue_com

my-media-library-wpdaxue_com

如果誰知道如何修正多媒體管理界面的媒體數量顯示,希望告知。

如果大傢不想折騰代碼的,也可以試試 View Own Posts Media Only 外掛。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *