By default the WordPress Media Library allows you to filter results by their type or date. How can I add a third drop down to list and filter by author?

Currently we have this:

enter image description here

I’d like to have the following:

enter image description here

According to this ticket (unless I’m reading it wrong) the code was added three years ago to /wp-admin/includes/class-wp-media-list-table.php to allow this, but I don’t see how this actually works.

The codex also says that it’s possible to modify the media library modal window you get when editing a page or post with:

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;
}

So I’d think that it’s possible to do something similar on the main Media Library page, but I can’t see how.

2 s
2

In your question you showed the image which is grid-view and that codex belongs to list-view. So I am confused here for which section you are talking about.

Grid View : not possible unless you change the core as they don’t provide any hook and the whole media section was created by jquery, backbone and unserscore. Please look into media-grid.min.js or media-grid.js for code.

List View : in this view you can easily add dropdown. here is the script to do this. If you want then add parse_query or pre_get_posts filter to change the query for the dropdown. As I am setting author to url, wordpress itself sets it for me so need for those filters.

function media_add_author_dropdown()
{
    $scr = get_current_screen();
    if ( $scr->base !== 'upload' ) return;

    $author   = filter_input(INPUT_GET, 'author', FILTER_SANITIZE_STRING );
    $selected = (int)$author > 0 ? $author : '-1';
    $args = array(
        'show_option_none'   => 'All Authors',
        'name'               => 'author',
        'selected'           => $selected
    );
    wp_dropdown_users( $args );
}
add_action('restrict_manage_posts', 'media_add_author_dropdown');

Here are the references

  1. restrict_manage_posts
  2. pre_get_posts
  3. parse_query

Edit #1: Added author filter after this comment

function author_filter($query) {
    if ( is_admin() && $query->is_main_query() ) {
        if (isset($_GET['author']) && $_GET['author'] == -1) {
            $query->set('author', '');
        }
    }
}
add_action('pre_get_posts','author_filter');

Leave a Reply

Your email address will not be published. Required fields are marked *