How to load attachment in media library for current user?

i’m using (media library) in my theme on Frontend.

It’s possible load only attachment of current user logged? For example, my wp user id is 55 and load only my attachment and not others by different users?

There isn’t a documentation about how work js in WP…

2 Answers
2

If you want to filter the attachments only at the moment they are being loaded via AJAX, for example when you are setting the post featured image, you can make use of:


function filter_get_the_user_attachments( $query ) {

    $current_user = wp_get_current_user();

    if ( !$current_user ) {
        return;
    }

    $current_user_id = $current_user->ID;

    $query['author__in'] = array(
        $current_user_id
    );

    return $query;

};

add_filter( 'ajax_query_attachments_args', 'filter_get_the_user_attachments', 10 );

Similar to the snippet found in the previous answer but faster.

Also, if you need to filter the attachments which are loaded at the upload.php page you can make use of:


function action_get_the_user_attachments( $query ) {

    // If we are not seeing the backend we quit.
    if ( !is_admin() ) {
        return;
    }

    /**
     * If it's not a main query type we quit.
     *
     * @link    https://codex.wordpress.org/Function_Reference/is_main_query
     */
    if ( !$query->is_main_query() ) {
        return;
    }

    $current_screen = get_current_screen();

    $current_screen_id = $current_screen->id;

    // If it's not the upload page we quit.
    if ( $current_screen_id != 'upload' ) {
        return;
    }

    $current_user = wp_get_current_user();

    $current_user_id = $current_user->ID;

    $author__in = array(
        $current_user_id
    );

    $query->set( 'author__in', $author__in );

}

add_action( 'pre_get_posts', 'action_get_the_user_attachments', 10 );

Hope this helps.

Leave a Comment