在媒体库网格模式下将自定义类添加到附件

时间:2016-04-10 作者:Matthias Günter

enter image description here

在上面的屏幕截图中,我们在media library with grid mode active. 我想根据附件筛选器添加自定义类wp_prepare_attachment_for_js.

例如,我钩住过滤器:

public function wp_prepare_attachment_for_js($response, $attachment, $meta) {
    $response[\'customClass\'] = "i-want-this-class";
    return $response;
}
也许它与脊梁有关。js是否要挂接到渲染过程中?还是需要解决ajaxComplete 然后等到渲染完成?

1 个回复
最合适的回答,由SO网友:Luis Sanz 整理而成

添加到媒体库网格中每个元素的类在media-views.js 文件尤其是,呈现元素的代码是wp.media.view.Attachment 作用这是一根脊梁。js视图,因此可以扩展该视图的库,以便向网格元素添加所需的类或其他属性。

首先是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\' );
然后是javascript文件:

(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);