wordpress show only media user has uploaded in wp_editor
Asked Answered
F

3

7

I'm creating a wordpress site where the registered user has the ability to create his own post via wp_editor() on the frontend, but just one post.

Now I want to restrict the user to be able to only see his uploaded media. I use the following script in the functions.php, which works in the backend. So if a user goes to the media section in the backend he will only see his uploaded media.

But if the user goes to "insert media" pop-up on the frontend wp_editor he can still see the uploaded media from all the users.

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

Do you have any idea hot to solve this annoyance? Thank you!

Fascinating answered 15/3, 2013 at 13:56 Comment(0)
H
13

You might try this plugin: http://wordpress.org/extend/plugins/view-own-posts-media-only/

Alternatively try this:

add_action('pre_get_posts','ml_restrict_media_library');

function ml_restrict_media_library( $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_media_library') )
    $wp_query_obj->set('author', $current_user->ID );
    return;
}

Source: http://wpsnipp.com/index.php/functions-php/restricting-users-to-view-only-media-library-items-they-upload/#comment-810649773

Harilda answered 15/3, 2013 at 14:15 Comment(0)
L
8

alternatively since WordPress 3.7

add_filter( 'ajax_query_attachments_args', "user_restrict_media_library" );
function user_restrict_media_library(  $query ) {
    global $current_user;
    $query['author'] = $current_user->ID ;
    return $query;
}
Leotaleotard answered 11/2, 2014 at 19:12 Comment(1)
A slightly different method is now provided in the documentation: codex.wordpress.org/Plugin_API/Filter_Reference/…Princedom
P
6

I use API/Filter Reference/ajax query attachments args for WP 4.3.1 and works

add_filter( 'ajax_query_attachments_args', 'show_current_user_attachments', 10, 1 );

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

just add on functions.php

or check this link WP Codex

Phylloid answered 20/10, 2015 at 21:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.