
Filter Hook since 2.1.0
wp_generate_attachment_metadata
Filters the generated attachment metadata array
Description
wp_generate_attachment_metadata is where WordPress hands you the finished sizes/EXIF metadata array for a fresh upload — the standard place to add your own custom fields to that structure.
When it runs
Runs inside wp_generate_attachment_metadata(), after WordPress has generated intermediate image sizes and read EXIF data, before the array is saved as post meta.
Signature
apply_filters( 'wp_generate_attachment_metadata', array $metadata, int $attachment_id, string $context );Parameters
metadataarray — The generated attachment metadata (sizes, width, height, EXIF).attachment_idint — The attachment post ID the metadata belongs to.contextstring — Either 'create' (new upload) or 'update' (metadata regeneration).
Examples
Basic
add_filter( 'wp_generate_attachment_metadata', function( $metadata, $attachment_id ) {
$metadata['custom_processed'] = true;
return $metadata;
}, 10, 2 );Add a custom flag to the metadata array.
Real case
add_filter( 'wp_generate_attachment_metadata', function( $metadata, $attachment_id ) {
if ( isset( $metadata['width'], $metadata['height'] ) ) {
$metadata['aspect_ratio'] = round( $metadata['width'] / $metadata['height'], 2 );
}
return $metadata;
}, 10, 2 );Precompute and store an aspect ratio for later use in templates.
Edge case
add_filter( 'wp_generate_attachment_metadata', function( $metadata, $attachment_id, $context ) {
if ( 'update' === $context ) {
return $metadata; // skip on manual 'Regenerate Thumbnails' runs
}
return $metadata;
}, 10, 3 );Distinguish a first-time upload from a later thumbnail-regeneration pass using $context.
Common Use Cases
- Add custom fields to attachment metadata
- Precompute derived values (aspect ratio, dominant color) at upload time
- Sync image metadata to an external DAM or CDN
- Filter which generated sizes actually get kept
Common mistakes
- Forgetting to return $metadata — an unreturned or null value wipes out the entire generated sizes array
- Not checking $context, which can cause expensive logic to re-run on every manual thumbnail regeneration, not just new uploads
Related hooks
FAQ
What happens if I forget to return the metadata array?
The attachment loses its generated sizes and dimension data — always return $metadata, even unmodified.
Does this run on every page load for existing images?
No — only when metadata is generated or explicitly regenerated (new upload, or a 'Regenerate Thumbnails' action), not on normal display.
Source: wp-admin/includes/image.php