사용자가 업로드 한 미디어 라이브러리 항목 만 보도록 제한합니까?


46

add_cap('upload_files')미디어 라이브러리는 사용자가 자신의 프로필 페이지를 사용하여 사진을 업로드 할 수 있기를 원합니다 . 미디어 라이브러리에는 업로드 된 모든 이미지가 표시됩니다. 어떻게 그들이 이미지 만 볼 수 있도록 그것을 필터링 할 수 있습니다 그들이 업로드를?

여기에 대한 해결책이 있습니다 ... 간단한 WP 쿼리를 수행 한 다음 사용자의 "프로필"페이지에서 루프를 수행합니다.

$querystr = " SELECT wposts.post_date,wposts.post_content,wposts.post_title, guid 
FROM $wpdb->posts wposts
WHERE wposts.post_author = $author 
AND wposts.post_type = 'attachment' 
ORDER BY wposts.post_date DESC";

$pageposts = $wpdb->get_results($querystr, OBJECT);

1
자신의 문제에 대한 답변을 찾으면 질문 자체가 아니라 아래 답변으로 추가하는 것이 좋습니다. 이것은 시스템에 더 적합하며, 귀하의 답변을 찬성하여이 사이트에 대한 귀하의 명성을 향상시킬 수 있습니다.
— Jan Fabry


'View Own Posts Media Only'플러그인을 두 번째로 사용해야합니다 .jquery 또는 php / html / css 솔루션을 어디서나 찾은 후 완벽하게 작동했습니다.
— waffl

답변:


37

pre_get_posts먼저 페이지와 사용자 기능을 결정하고 특정 조건이 충족 될 때 author 매개 변수를 설정 하는 필터를 사용하여 미디어 목록을 필터링 할 수 있습니다.

예

add_action('pre_get_posts','users_own_attachments');
function users_own_attachments( $wp_query_obj ) {

    global $current_user, $pagenow;

    $is_attachment_request = ($wp_query_obj->get('post_type')=='attachment');

    if( !$is_attachment_request )
        return;

    if( !is_a( $current_user, 'WP_User') )
        return;

    if( !in_array( $pagenow, array( 'upload.php', 'admin-ajax.php' ) ) )
        return;

    if( !current_user_can('delete_pages') )
        $wp_query_obj->set('author', $current_user->ID );

    return;
}

관리자 및 편집자가 여전히 전체 미디어 목록을 볼 수 있도록 페이지 삭제 제한을 조건으로 사용했습니다.

하나의 작은 부작용이 있는데, 후크를 볼 수 없으며 미디어 목록 위에 표시된 첨부 파일 수와 함께 있습니다 (이는 주어진 사용자가 아닌 미디어 항목의 총 수를 계속 표시합니다-i 'd 그래도 이것을 사소한 문제로 생각하십시오).

내가 모두 똑같이 게시한다고 생각하면 유용 할 것입니다 ..;)


가입자 수준의 사용자에게 파일 업로드를 허용했습니다. 코드를 사용하려고했지만 작동하지 않습니다.
— Sisir

1
"작동하지 않음"은 그다지 많지 않습니다.
— t31os

같은 관찰을 확인할 수 있습니다. 나에게 "작동하지 않음"은 "기고자"역할이 jpg를 업로드 할 때 모든 미디어 항목을 계속 볼 수 있음을 의미합니다. 그러나 메뉴에서 미디어 라이브러리로 이동하면 비어 있습니다. ( 내 "기여자"역할에는 이미 파일을 업로드 할 수있는 추가 기능이 있으며 작동합니다. )
— Sparky

따라서 업로드 창의 "미디어 라이브러리"탭을 채우는 모든 페이지에 대해 코드를 수정하면됩니다. 나는 이것을 지금 연구하고 있습니다.
— Sparky

올바르게 기억하고 실수가 발생하면이 답변을 작성할 당시 적절한 후크가 없었으며 미디어 수를 수정하는 후크가 없었던 것과 유사합니다. 그러나 글을 쓰는 시점부터 3 가지 새로운 버전의 WordPress가 있었으므로 이제 솔루션을 사용할 수 있습니다.
— t31os

32

WP 3.7 ajax_query_attachments_args부터 문서 를 통해 제공되는 필터 를 통한 훨씬 더 나은 방법 이 있습니다 .

add_filter( 'ajax_query_attachments_args', 'show_current_user_attachments' );

function show_current_user_attachments( $query ) {
    $user_id = get_current_user_id();
    if ( $user_id ) {
        $query['author'] = $user_id;
    }
    return $query;
}

19

다음은 게시물과 미디어 모두를위한 완벽한 솔루션입니다 (이 코드는 특별히 저자를위한 것이지만 모든 사용자 역할에 따라 변경할 수 있습니다). 또한 코어 파일을 해킹하지 않고 포스트 / 미디어 수를 수정합니다.

// Show only posts and media related to logged in author
add_action('pre_get_posts', 'query_set_only_author' );
function query_set_only_author( $wp_query ) {
    global $current_user;
    if( is_admin() && !current_user_can('edit_others_posts') ) {
        $wp_query->set( 'author', $current_user->ID );
        add_filter('views_edit-post', 'fix_post_counts');
        add_filter('views_upload', 'fix_media_counts');
    }
}

// Fix post counts
function fix_post_counts($views) {
    global $current_user, $wp_query;
    unset($views['mine']);
    $types = array(
        array( 'status' =>  NULL ),
        array( 'status' => 'publish' ),
        array( 'status' => 'draft' ),
        array( 'status' => 'pending' ),
        array( 'status' => 'trash' )
    );
    foreach( $types as $type ) {
        $query = array(
            'author'      => $current_user->ID,
            'post_type'   => 'post',
            'post_status' => $type['status']
        );
        $result = new WP_Query($query);
        if( $type['status'] == NULL ):
            $class = ($wp_query->query_vars['post_status'] == NULL) ? ' class="current"' : '';
            $views['all'] = sprintf(
            '<a href="%1$s"%2$s>%4$s <span class="count">(%3$d)</span></a>',
            admin_url('edit.php?post_type=post'),
            $class,
            $result->found_posts,
            __('All')
        );
        elseif( $type['status'] == 'publish' ):
            $class = ($wp_query->query_vars['post_status'] == 'publish') ? ' class="current"' : '';
            $views['publish'] = sprintf(
            '<a href="%1$s"%2$s>%4$s <span class="count">(%3$d)</span></a>',
            admin_url('edit.php?post_type=post'),
            $class,
            $result->found_posts,
            __('Publish')
        );
        elseif( $type['status'] == 'draft' ):
            $class = ($wp_query->query_vars['post_status'] == 'draft') ? ' class="current"' : '';
            $views['draft'] = sprintf(
            '<a href="%1$s"%2$s>%4$s <span class="count">(%3$d)</span></a>',
            admin_url('edit.php?post_type=post'),
            $class,
            $result->found_posts,
            __('Draft')
        );
        elseif( $type['status'] == 'pending' ):
            $class = ($wp_query->query_vars['post_status'] == 'pending') ? ' class="current"' : '';
            $views['pending'] = sprintf(
            '<a href="%1$s"%2$s>%4$s <span class="count">(%3$d)</span></a>',
            admin_url('edit.php?post_type=post'),
            $class,
            $result->found_posts,
            __('Pending')
        );
        elseif( $type['status'] == 'trash' ):
            $class = ($wp_query->query_vars['post_status'] == 'trash') ? ' class="current"' : '';
            $views['trash'] = sprintf(
            '<a href="%1$s"%2$s>%4$s <span class="count">(%3$d)</span></a>',
            admin_url('edit.php?post_type=post'),
            $class,
            $result->found_posts,
            __('Trash')
        );
        endif;
    }
    return $views;
}

// Fix media counts
function fix_media_counts($views) {
    global $wpdb, $current_user, $post_mime_types, $avail_post_mime_types;
    $views = array();
    $count = $wpdb->get_results( "
        SELECT post_mime_type, COUNT( * ) AS num_posts 
        FROM $wpdb->posts 
        WHERE post_type = 'attachment' 
        AND post_author = $current_user->ID 
        AND post_status != 'trash' 
        GROUP BY post_mime_type
    ", ARRAY_A );
    foreach( $count as $row )
        $_num_posts[$row['post_mime_type']] = $row['num_posts'];
    $_total_posts = array_sum($_num_posts);
    $detached = isset( $_REQUEST['detached'] ) || isset( $_REQUEST['find_detached'] );
    if ( !isset( $total_orphans ) )
        $total_orphans = $wpdb->get_var("
            SELECT COUNT( * ) 
            FROM $wpdb->posts 
            WHERE post_type = 'attachment'
            AND post_author = $current_user->ID 
            AND post_status != 'trash' 
            AND post_parent < 1
        ");
    $matches = wp_match_mime_types(array_keys($post_mime_types), array_keys($_num_posts));
    foreach ( $matches as $type => $reals )
        foreach ( $reals as $real )
            $num_posts[$type] = ( isset( $num_posts[$type] ) ) ? $num_posts[$type] + $_num_posts[$real] : $_num_posts[$real];
    $class = ( empty($_GET['post_mime_type']) && !$detached && !isset($_GET['status']) ) ? ' class="current"' : '';
    $views['all'] = "<a href='upload.php'$class>" . sprintf( __('All <span class="count">(%s)</span>', 'uploaded files' ), number_format_i18n( $_total_posts )) . '</a>';
    foreach ( $post_mime_types as $mime_type => $label ) {
        $class = '';
        if ( !wp_match_mime_types($mime_type, $avail_post_mime_types) )
            continue;
        if ( !empty($_GET['post_mime_type']) && wp_match_mime_types($mime_type, $_GET['post_mime_type']) )
            $class = ' class="current"';
        if ( !empty( $num_posts[$mime_type] ) )
            $views[$mime_type] = "<a href='upload.php?post_mime_type=$mime_type'$class>" . sprintf( translate_nooped_plural( $label[2], $num_posts[$mime_type] ), $num_posts[$mime_type] ) . '</a>';
    }
    $views['detached'] = '<a href="upload.php?detached=1"' . ( $detached ? ' class="current"' : '' ) . '>' . sprintf( __( 'Unattached <span class="count">(%s)</span>', 'detached files' ), $total_orphans ) . '</a>';
    return $views;
}

스 니펫은 훌륭하지만 미디어 라이브러리에 항목이없는 경우 오류가 발생합니다. 경고 : array_sum ()은 매개 변수 1이 배열, 널 (null)이 될 것으로 예상하고 경고 : array_keys ()는 매개 변수 1이 배열, 널 (null)이 될 것으로 예상합니다.
— chrismccoy

fix_media_counts () 함수에서 $ _num_posts를 배열로 정의하면됩니다. $_num_posts = array();
— Paul

4
이 답변의 코드는 작동하지만 고급 사용자 정의 필드 플러그인으로 만든 사용자 정의 필드도 제거합니다.
— Sparky


5

이것은 허용 된 답변 의 수정 된 버전입니다 . 허용 된 답변은 왼쪽의 미디어 메뉴 항목 만 대상으로하므로 사용자는 사진을 게시물에 업로드 할 때 모달 상자 내에서 전체 미디어 라이브러리를 볼 수 있습니다. 이 약간 수정 된 코드는 해당 상황을 해결합니다. 대상 사용자는 게시물 내에 나타나는 모달 상자의 미디어 라이브러리 탭에서 자신의 미디어 항목 만 볼 수 있습니다.

이것은 편집 할 줄을 표시하는 주석이있는 허용 된 답변의 코드입니다 ...

add_action('pre_get_posts','users_own_attachments');
function users_own_attachments( $wp_query_obj ) {

    global $current_user, $pagenow;

    if( !is_a( $current_user, 'WP_User') )
        return;

    if( 'upload.php' != $pagenow ) // <-- let's work on this line
        return;

    if( !current_user_can('delete_pages') )
        $wp_query_obj->set('author', $current_user->id );

    return;
}

사용자가 업로드 모달의 미디어 메뉴 및 미디어 라이브러리 탭에서만 자신의 미디어를 볼 수 있도록 표시된 행을 다음으로 바꿉니다.

if( (   'upload.php' != $pagenow ) &&
    ( ( 'admin-ajax.php' != $pagenow ) || ( $_REQUEST['action'] != 'query-attachments' ) ) )

( 가독성을 위해 줄 바꿈 및 간격 만 삽입 )

다음은 위와 동일하지만 게시물 메뉴 항목에서 자신의 게시물을 볼 수 없도록 제한합니다.

if( (   'edit.php' != $pagenow ) &&
    (   'upload.php' != $pagenow ) &&
    ( ( 'admin-ajax.php' != $pagenow ) || ( $_REQUEST['action'] != 'query-attachments' ) ) )

( 가독성을 위해 줄 바꿈 및 간격 만 삽입 )

참고 : 허용 된 답변과 마찬가지로 게시물과 미디어 카운터가 잘못되었습니다. 그러나이 페이지의 다른 답변에는이 솔루션이 있습니다. 나는 그것들을 테스트하지 않았기 때문에 그것들을 포함시키지 않았습니다.


2

완전한 작업 코드. 문제 추가는 게시물 추가 페이지의 미디어 라이브러리에서 잘못된 이미지 수를 얻는 것입니다.

function my_files_only( $wp_query ) {
if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/upload.php' ) !== false ) {
    if ( !current_user_can( 'level_5' ) ) {
        global $current_user;
        $wp_query->set( 'author', $current_user->id );
    }
}
else if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/media-upload.php' ) !== false ) {
    if ( !current_user_can( 'level_5' ) ) {
        global $current_user;
        $wp_query->set( 'author', $current_user->id );
    }
}
}
add_filter('parse_query', 'my_files_only' );

2
사용자 수준을 사용해서는 안되며, 여전히 WP 2.0 이전 버전과의 호환성을 위해 WordPress에 있으며, 최신 WordPress에서 사용자 기능을 결정하기에 신뢰할 수 없습니다 (호환성이 더 이상 필요하지 않을 때 코어에서 사라질 수 있음) ). 실제 기능 을 사용하여 사용자 권한을 결정 하십시오 .
— t31os

을 포함 media-upload.php하더라도 코드가 포스트 편집 페이지에서 생성 된 업로드 모달에서 작동하지 않습니다. 여전히 모든 라이브러리 항목을 볼 수 있습니다.
— Sparky

2

t31os에는 훌륭한 솔루션이 있습니다. 유일한 것은 모든 게시물의 수가 여전히 표시된다는 것입니다.

jQuery를 사용하여 숫자 수가 표시되지 않도록하는 방법을 알아 냈습니다.

이것을 함수 파일에 추가하십시오.

    function jquery_remove_counts()
{
    ?>
    <script type="text/javascript">
    jQuery(function(){
        jQuery("ul.subsubsub").find("span.count").remove();
    });
    </script>
    <?php
}
add_action('admin_head', 'jquery_remove_counts');

나를 위해 일하고 있습니다!


1

나는 꽤 거칠지 만 실행 가능한 솔루션으로 내 문제를 해결했습니다.

1) WP Hide Dashboard 플러그인을 설치 했으므로 사용자는 자신의 프로필 편집 양식에 대한 링크 만 볼 수 있습니다.

2) author.php 템플릿 파일에 위에서 사용한 코드를 삽입했습니다.

3) 그런 다음 로그인 한 사용자의 경우 업로드 페이지 "wp-admin / media-new.php"에 대한 직접 링크를 표시했습니다.

4) 다음으로 주목 한 것은 사진을 업로드 한 후 upload.php로 리디렉션하고 다른 모든 사진을 볼 수 있다는 것입니다. media-new.php 페이지에 대한 링크를 찾지 못하여 코어 "media-upload.php"를 해킹하여 프로필 페이지로 리디렉션했습니다.

    global $current_user;
    get_currentuserinfo();
    $userredirect =  get_bloginfo('home') . "/author/" .$current_user->user_nicename;

그리고 교체 wp_redirect( admin_url($location) );와 함께wp_redirect($userredirect);

그러나 몇 가지 문제가 있습니다. 먼저, 로그인 한 사용자는 "upload.php"로 이동해도됩니다 (있는 경우). 그들은 파일에서 LOOK를 제외하고는 아무것도 할 수 없으며 99 %의 사람들은 그것에 대해 알지 못하지만 여전히 최적은 아닙니다. 둘째, 업로드 후 관리자를 프로필 페이지로 리디렉션합니다. 사용자 역할을 확인하고 구독자 만 리디렉션하면 상당히 간단하게 해결할 수 있습니다.

핵심 파일에 들어 가지 않고 미디어 페이지에 연결하는 것에 대한 아이디어가 있다면 누구나 감사하겠습니다. 감사!


2
admin_init모든 관리자 요청에서 실행 되는 후크가 있습니다. 사용자가 upload.php를 요청하고 해당 요청을 차단 wp_die('Access Denied')하거나 (예 :) 후크 당 유효한 위치로 리디렉션 하지 못하게하려는 경우 .
— hakre

1
<?php
/*
Plugin Name: Manage Your Media Only
Version: 0.1
*/

//Manage Your Media Only
function mymo_parse_query_useronly( $wp_query ) {
    if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/upload.php' ) !== false ) {
        if ( !current_user_can( 'level_5' ) ) {
            global $current_user;
            $wp_query->set( 'author', $current_user->id );
        }
    }
}

add_filter('parse_query', 'mymo_parse_query_useronly' );
?>

위의 코드를 manage_your_media_only.php로 저장하고 압축 한 다음 플러그인으로 WP에 업로드하고 활성화하면됩니다.


1

이를 수행하는 한 가지 방법은 Role Scoper 플러그인 을 사용하는 것입니다. 매우 구체적인 역할 및 기능을 관리하는 데에도 좋습니다. 실제로 미디어 라이브러리의 이미지에 대한 액세스를 각 사용자가 업로드 한 이미지에만 잠글 수 있습니다. 나는 현재 진행중인 프로젝트에 사용하고 있으며 잘 작동합니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.