image_editor_output_format │ хук-фильтр │ WP 5.8.0

Позволяет изменить формат, в котором редактор WordPress сохраняет обработанные изображения и создаваемые размеры.

Фильтр получает массив вида исходный MIME-тип => выходной MIME-тип. По умолчанию WordPress преобразует HEIC и HEIF в JPEG:

[
	'image/heic'          => 'image/jpeg',
	'image/heif'          => 'image/jpeg',
	'image/heic-sequence' => 'image/jpeg',
	'image/heif-sequence' => 'image/jpeg',
]

Преобразование выполняется только в формат, поддерживаемый используемым редактором изображений.

При клиентской обработке (добавленной в WP 7.1) WordPress применяет эти правила в браузере перед загрузкой созданных размеров.

При добавлении своих правил изменяйте полученный массив, а не заменяйте его целиком. Иначе можно удалить стандартное преобразование HEIC/HEIF в JPEG.

При клиентской обработке преобразование прозрачного PNG в JPEG пропускается, чтобы сохранить прозрачность. UltraHDR JPEG также не преобразуется, поскольку смена формата удалит HDR-карту.

Использование

add_filter( 'image_editor_output_format', 'image_editor_output_format_filter', 10, 3 );

/**
 * Filters the image editor output format mapping.
 *
 * @param array $output_format  An array of mime type mappings. Maps a source mime type to a new
 *                              destination mime type. By default maps HEIC/HEIF input to JPEG output.
 * @param string $filename      Path to the image.
 * @param string $mime_type     The source image mime type.
 */
function image_editor_output_format_filter( $output_format, $filename, $mime_type ){
	// filter...
	return $output_format;
}
$output_format(string[])
Массив преобразований вида исходный MIME-тип => выходной MIME-тип.
$filename(string)
Путь к исходному изображению. Может быть пустой строкой, если путь недоступен в текущем контексте.
$mime_type(string)
MIME-тип исходного изображения.

Примеры

#1 Преобразование JPEG в WebP

Сохраняет размеры JPEG-изображений в формате WebP.

add_filter( 'image_editor_output_format', 'kama_convert_jpeg_to_webp' );

function kama_convert_jpeg_to_webp( $formats ) {
	$formats['image/jpeg'] = 'image/webp';

	return $formats;
}

#2 Преобразование JPEG, PNG, WebP и HEIC/HEIF в AVIF

Сохраняет создаваемые размеры поддерживаемых изображений в формате AVIF.

add_filter( 'image_editor_output_format', 'kama_convert_images_to_avif' );

function kama_convert_images_to_avif( $formats ) {
	$source_formats = [
		'image/jpeg',
		'image/png',
		'image/webp',
		'image/heic',
		'image/heif',
		'image/heic-sequence',
		'image/heif-sequence',
	];

	foreach ( $source_formats as $source_format ) {
		$formats[ $source_format ] = 'image/avif';
	}

	return $formats;
}

Обработка HEIC/HEIF и сохранение в AVIF должны поддерживаться используемой библиотекой обработки изображений.

#3 Преобразование только определённого файла

Преобразует JPEG в WebP только для изображений из каталога products.

add_filter( 'image_editor_output_format', 'kama_convert_product_images', 10, 3 );

function kama_convert_product_images( $formats, $filename, $mime_type ) {
	if (
		'image/jpeg' === $mime_type
		&& str_contains( wp_normalize_path( $filename ), '/products/' )
	) {
		$formats['image/jpeg'] = 'image/webp';
	}

	return $formats;
}

#4 Отключение преобразования форматов

Отключает пользовательские правила и стандартное преобразование HEIC/HEIF в JPEG.

add_filter( 'image_editor_output_format', 'kama_disable_image_format_conversion' );

function kama_disable_image_format_conversion() {
	return [];
}

Список изменений

С версии 5.8.0 Введена.
С версии 6.7.0 The default was changed from an empty array to an array containing the HEIC/HEIF images mime types.

Где вызывается хук

wp_get_image_editor_output_format()
image_editor_output_format
WP_REST_Attachments_Controller::prepare_item_for_response()
image_editor_output_format
wp-includes/media.php 6567
return apply_filters( 'image_editor_output_format', $output_format, $filename, $mime_type );
wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php 1587-1592
$output_formats = apply_filters(
	'image_editor_output_format',
	array( $mime_type => $mime_type ),
	$filename ? $filename : '',
	$mime_type
);
wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php 1611-1616
$output_formats = apply_filters(
	'image_editor_output_format',
	array( $mime_type => $mime_type ),
	$filename ? $filename : '',
	$mime_type
);

Где используется хук в WordPress

wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php 2794
add_filter( 'image_editor_output_format', '__return_empty_array', 100 );
wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php 2840
remove_filter( 'image_editor_output_format', '__return_empty_array', 100 );
wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php 534
add_filter( 'image_editor_output_format', '__return_empty_array', 100 );
wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php 803
remove_filter( 'image_editor_output_format', '__return_empty_array', 100 );