Задача
Получить изображение в размере, добавленном через add_image_size, в JavaScript объекте после успешной загрузки через Media Uploader Dialog. Как можно заметить, его там нет по умолчанию.
Код для создания и вызова диалога для загрузки/выбора картинки может выглядеть так:
jQuery('input.guide-logo-upload').on('click', function( event ){ event.preventDefault(); if ( file_frame ) { file_frame.open(); return; } file_frame = wp.media.frames.file_frame = wp.media({ title: jQuery( this ).data( 'uploader_title' ), button: { text: jQuery( this ).data( 'uploader_button_text' ) }, multiple: false }); file_frame.on( 'select', function() { attachment = file_frame.state().get('selection').first().toJSON(); jQuery('input#g-logo').val( attachment.url ); jQuery('input#g-logo-id').val( attachment.id ); jQuery('p.logo-description').after( '' ); jQuery('p.logo-description').after( '
' ); }); file_frame.open();
Решение
Следующий фильтр добавляет все не стандартные размеры изображений в объект возвращаемый WordPress загрузчиком:
function my_image_sizes_for_js( $response, $attachment, $meta ){ $size_array = array( 'custom_size_one', 'custom_size_two') ; foreach ( $size_array as $size ): if ( isset( $meta['sizes'][ $size ] ) ) { $attachment_url = wp_get_attachment_url( $attachment->ID ); $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url ); $size_meta = $meta['sizes'][ $size ]; $response['sizes'][ $size ] = array( 'height' => $size_meta['height'], 'width' => $size_meta['width'], 'url' => $base_url . $size_meta['file'], 'orientation' => $size_meta['height'] > $size_meta['width'] ? 'portrait' : 'landscape', ); } endforeach; return $response; } add_filter ( 'wp_prepare_attachment_for_js', 'my_image_sizes_for_js' , 10, 3 );