Add custom class to attachment in media library grid mode

The classes added to each element in the media library grid are dinamically generated in the media-views.js file. Particularly, the code that renders the elements is part of the wp.media.view.Attachment function. It’s a Backbone.js view, so it’s possible to extend the library of that view in order to add the classes or other attributes you need to the grid elements.

First the php:

//Pass the variable to the javascript file
function wpse223259_filter_wp_prepare_attachment_for_js( $response, $attachment, $meta ) {

    $response['customClass'] = "i-want-this-class";

    return $response;

};

add_filter( 'wp_prepare_attachment_for_js', 'wpse223259_filter_wp_prepare_attachment_for_js', 10, 3 );


//Enqueue the javascript file that will extend the view
function wpse223259_add_class_to_media_library_grid_elements() {

    $currentScreen = get_current_screen();

    if( 'upload' === $currentScreen->id ) :

        global $mode;

        if( 'grid' === $mode ) :

            wp_enqueue_script( 'add-class-to-media-library-grid-elements', 'your/path/to/the/javascript-file.js', array( 'jquery' ) ); //Edit to match the file location

        endif;

    endif;

}

add_action( 'admin_enqueue_scripts', 'wpse223259_add_class_to_media_library_grid_elements' );

And then the javascript file:

(function($) {

    $(document).ready( function() {

        if ( undefined !== wp.media ) {

            wp.media.view.Attachment.Library = wp.media.view.Attachment.Library.extend({
                className: function () { return 'attachment ' + this.model.get( 'customClass' ); }
            });

        }

    });

})(jQuery);

Leave a Comment