添加到媒体库网格中每个元素的类在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);