Hook into attachment metadata filter while uploading an image

Example of how hook into the attachment metadata while uploading an attachment, in this case to modify the metadata.

This example checks if the attachment being uploaded is a webP image, and if yes, then set a custom thumbnail metadata. This specific example was needed before WordPress 5.8, when WordPress didn’t work with webP images. This specific example is no longer needed, but serves as a good example for how to hook into and change attachment metadata, including modifying the thumbnail URL, while uploading an image.

 * When a webp image is uploaded, save the attachment metadata,
 * including metadata for a thumbnail size file
add_filter('wp_generate_attachment_metadata', function ($metadata, $attachment_id, $context) {
	if('create' !== $context || ! empty($metadata)) return $metadata;

	$post = get_post( $attachment_id );
	if ( ! $post ) return $metadata;

	if('image/webp' !== $post->post_mime_type) return $metadata;
	$original_filename = basename($post->guid);

	$dir = wp_get_upload_dir()['basedir'];

    $size = getimagesize("$dir/$original_filename");

    if(empty($size[0]) && empty($size[1])) return $metadata;

    // manually set thumbnail meta which i upload manually to uploads dir
    $thumbname = str_replace('.webp', '-350x100.webp', $original_filename);

    return array(
		'width' => $size[0],
		'height' => $size[1],
		'file' => $original_filename,
		'original_image' => $original_filename,
		'sizes' => array(
            'thumbnail' => array(
                    'file' => $thumbname,
                    'width' => '350',
                    'height' => '100',
                    'mime-type' => 'image/webp'
}, 10, 3);

See more:

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this: