enter image description here

In the above screenshot we are in the media library with grid mode active. I want to add a custom class depending on the attachment filter wp_prepare_attachment_for_js.

For example i hook to the filter:

public function wp_prepare_attachment_for_js($response, $attachment, $meta) {
    $response['customClass'] = "i-want-this-class";
    return $response;

Perhaps it works with Backbone.js to hook into the render process? Or does it need a workaround with ajaxComplete and wait until it is rendered?

1 Answer 1


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




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




Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.