wp_get_attachment_metadata( int $attachment_id = 0, bool $unfiltered = false ): array|false
- Since
- 2.1.0, 6.0.0
- Source
wp-includes/post.php:6890
Reads the array stored in an attachment's _wp_attachment_metadata post meta, covering width, height, file path, registered sizes, and image metadata. Returns false when no attachment can be resolved or when the stored value isn't an array, and skips the wp_get_attachment_metadata filter entirely when the $unfiltered argument is true. Pair it with wp_generate_attachment_metadata() when you need to create or refresh that stored array rather than just read it.
Compatibility
- WordPress
- since 6.0.0
- PHP
- 7.4–8.6-dev
- 6.7.7
- 6.8.8
- 6.9.7
- 7.0.4
- 7.1.0
Present in every tracked release (6.7.7 to 7.1.0), and compiles on PHP 7.4 through 8.6-dev.
Parameters
$attachment_idintoptional- Attachment post ID. Defaults to global $post.Default:
0 $unfilteredbooloptional- If true, filters are not run. Default false.Default:
false
Return value
array|false- Attachment metadata. False on failure.
$widthintThe width of the attachment.$heightintThe height of the attachment.$filestringThe file path relative towp-content/uploads.$sizesarrayKeys are size slugs, each value is an array containing 'file', 'width', 'height', and 'mime-type'.$image_metaarrayImage metadata.$filesizeintFile size of the attachment.
Code examples
Every example is editable and runs in a real WordPress booted in your browser by WordPress Playground. Press Run, then edit the code: clicking away re-runs it. Nothing is sent anywhere until you do.
Get the width, height, and file path of an image attachment
Look up a sample image attachment and print the dimensions and relative file path stored in its metadata.
$attachments = get_posts( array(
'post_type' => 'attachment',
'title' => 'Mountain Sunrise',
'posts_per_page' => 1,
) );
if ( $attachments ) {
$metadata = wp_get_attachment_metadata( $attachments[0]->ID );
if ( $metadata ) {
printf(
'Image is %d by %d pixels, stored at %s',
(int) $metadata['width'],
(int) $metadata['height'],
esc_html( $metadata['file'] )
);
} else {
echo 'No metadata found for this attachment.';
}
} else {
echo 'Attachment not found.';
}In a real upload this metadata array would come from wp_generate_attachment_metadata() instead of being written by hand.
Add a custom field to attachment metadata via the filter, and see it disappear with $unfiltered
Register a filter that appends a photographer credit to every attachment's metadata, then compare the filtered and unfiltered results for the same attachment.
add_filter(
'wp_get_attachment_metadata',
function ( $data, $attachment_id ) {
$data['photographer_credit'] = 'J. Rivera';
return $data;
},
10,
2
);
$attachments = get_posts( array(
'post_type' => 'attachment',
'title' => 'Studio Portrait',
'posts_per_page' => 1,
) );
if ( $attachments ) {
$id = $attachments[0]->ID;
$filtered = wp_get_attachment_metadata( $id );
$unfiltered = wp_get_attachment_metadata( $id, true );
echo 'Filtered credit: ' . esc_html( $filtered['photographer_credit'] ?? '(missing)' ) . '<br>';
echo 'Unfiltered credit: ' . esc_html( $unfiltered['photographer_credit'] ?? '(missing)' );
} else {
echo 'Attachment not found.';
}The unfiltered call passes true as the second argument, so it returns the raw stored array and never sees the added key.
Common problems and fixes · 4
- Why does wp_get_attachment_metadata return false for an attachment I know exists?
- Why am I getting the wrong data when I call this without an ID inside a template?
- Why did my sizes array get wiped out after adding a filter on wp_get_attachment_metadata?
- Why isn't my filter's extra data showing up when I call this function?
Why does wp_get_attachment_metadata return false for an attachment I know exists?
Why am I getting the wrong data when I call this without an ID inside a template?
Why did my sizes array get wiped out after adding a filter on wp_get_attachment_metadata?
Why isn't my filter's extra data showing up when I call this function?
Alternatives and related functions
wp_generate_attachment_metadata- When you need to create or regenerate the metadata array itself (for example after a new upload or a manual regeneration), rather than just read what's already stored.
wp_update_attachment_metadata- When you need to write a modified metadata array back to the '_wp_attachment_metadata' meta key instead of reading it.
wp_get_attachment_image_src- When you just need a usable URL, width, and height for one registered image size rather than the full stored metadata array.
wp_get_attachment_url- When you only need the attachment's file URL and don't care about dimensions, sizes, or image metadata.
Performance profile
How much work a call to wp_get_attachment_metadata() does, and what it touches: the algorithmic scaling, the Zend instruction count per call across PHP versions, the hooks it hands control to, and the core code that calls it. Measured from the compiled opcodes, not a stopwatch, so every number is identical on any machine running the same PHP version, and every function in core is ranked by cost.
- Cost class
- Heavy
- Scaling
- Constant
- Instructions
- 10–24
- Plugin surface
- 1 hook
- Called by
- 39
Reaches the database via get_post().
No loop in the body: the same number of instructions runs whatever you pass in.
Executed per call on PHP 8.5, depending on the branch taken. The body compiles to 27.
Third-party callbacks on 'wp_get_attachment_metadata' run inside this call, and their cost is not bounded by anything here.
39 places in core call this, so the cost is paid more often than your own code shows.
What it touches
- querycontent query
get_post()called directly - hookthird-party callbacks
apply_filters()called directly
Further down the call graph this can also reach cache, serialize, option and transient. Those are the worst case, several calls deep and usually down an error path, not what a normal call pays.
What one call costs · 5 distinct outcomes
One number would be a lie: the work depends on which branch runs. These are every distinct cost wp_get_attachment_metadata() can have, taken from its control-flow graph on PHP 8.5.
| When | Instructions | Calls it makes |
|---|---|---|
| always | 10 | get_post() |
| always | 13–14 | get_post_meta() |
| always | 18–19 | get_post(), get_post_meta() |
| always | 19 | get_post_meta(), apply_filters() |
| always | 24 | get_post(), get_post_meta(), apply_filters() |
Across PHP versions
Compiles the same on PHP 7.4, 8.1, 8.2, 8.3, 8.4, 8.5 and 8.6-dev: 27 instructions, 10–24 executed per call, 4 branches. The work does not change between versions.
An instruction is not a fixed amount of time, so a matching count is not necessarily the same speed; what it rules out is a difference in the work itself.
Hooks and filters fired · 1
One hook fires while wp_get_attachment_metadata() runs, in this order:
- apply_filters( wp_get_attachment_metadata )filterline 6921 (+31 into the body)
Filters the attachment meta data.
Uses · 3
- get_post()Retrieves post data given a post ID or post object.
- get_post_meta()Retrieves a post meta field for the given post ID.
- apply_filters()Calls the callback functions that have been added to a filter hook.
Used by · 39
- Custom_Image_Header::step_2()Displays second step of custom header image page.
- WP_Customize_Manager::import_theme_starter_content()Imports theme starter content into the customized state.
- WP_REST_Attachments_Controller::edit_media_item()Applies edits to a media item and creates a new attachment record.
- WP_REST_Attachments_Controller::prepare_item_for_response()Prepares a single attachment output for response.
- WP_Widget_Media_Image::render_media()Render the media on the frontend.
- attachment_id3_data_meta_box()Displays fields for ID3 data.
- attachment_submitbox_metadata()Displays non-editable attachment metadata in the publish meta box.
- block_core_image_render_lightbox()Adds the directives and layout needed for the lightbox behavior.
- edit_form_image_editor()Displays the image and editor in the post editor
- edit_post()Updates an existing post with values provided in `$_POST`.
- gallery_shortcode()Builds the Gallery shortcode output.
- get_media_item()Retrieves HTML form for modifying the image attachment.
Show all 39
- get_uploaded_header_images()Gets the header images uploaded for the active theme.
- image_downsize()Scales an image to fit a particular size (such as 'thumb' or 'medium').
- image_get_intermediate_size()Retrieves the image's intermediate size (resized) path, width, and height.
- prepend_attachment()Wraps attachment in paragraph tag before content.
- render_block_core_video()Renders the `core/video` block on the server to supply the width and height attributes from the attachment metadata.
- twenty_twenty_one_get_attachment_image_attributes()Filters the list of attachment image attributes.
- twentyfifteen_entry_meta()Prints HTML with meta information for the categories, tags.
- wp_ajax_save_attachment()Handles updating attachment attributes via AJAX.
- wp_calculate_image_sizes()Creates a 'sizes' attribute value for an image.
- wp_delete_attachment()Trashes or deletes an attachment.
- wp_get_attachment_image()Gets an HTML img element representing an image attachment.
- wp_get_attachment_image_sizes()Retrieves the value for an image attachment's 'sizes' attribute.
- wp_get_attachment_image_srcset()Retrieves the value for an image attachment's 'srcset' attribute.
- wp_get_attachment_thumb_file()Retrieves thumbnail for an attachment.
- wp_get_missing_image_subsizes()Compare the existing image sub-sizes (as saved in the attachment meta) to the currently registered image sub-sizes, and return the difference.
- wp_get_original_image_path()Retrieves the path to an uploaded image file.
- wp_get_original_image_url()Retrieves the URL to an original attachment image.
- wp_image_editor()Loads the WP image-editing interface.
- wp_img_tag_add_srcset_and_sizes_attr()Adds `srcset` and `sizes` attributes to an existing `img` HTML tag.
- wp_img_tag_add_width_and_height_attr()Adds `width` and `height` attributes to an `img` HTML tag.
- wp_maybe_generate_attachment_metadata()Maybe attempts to generate attachment metadata, if missing.
- wp_playlist_shortcode()Builds the Playlist shortcode output.
- wp_prepare_attachment_for_js()Prepares an attachment post object for JS, where it is expected to be JSON-encoded and fit into an Attachment model.
- wp_restore_image()Restores the metadata for a given attachment.
- wp_save_image()Saves image to post, along with enqueued changes in `$_REQUEST['history']`.
- wp_update_image_subsizes()If any of the currently registered image sub-sizes are missing, create them and update the image meta data.
- wp_xmlrpc_server::_prepare_media_item()Prepares media item data for return in an XML-RPC object.
Source code
function wp_get_attachment_metadata( $attachment_id = 0, $unfiltered = false ) { $attachment_id = (int) $attachment_id; if ( ! $attachment_id ) { $post = get_post(); if ( ! $post ) { return false; } $attachment_id = $post->ID; } $data = get_post_meta( $attachment_id, '_wp_attachment_metadata', true ); if ( ! $data ) { return false; } if ( $unfiltered ) { return $data; } /** * Filters the attachment meta data. * * @since 2.1.0 * * @param array $data Array of meta data for the given attachment. * @param int $attachment_id Attachment post ID. */ return apply_filters( 'wp_get_attachment_metadata', $data, $attachment_id );}Changelog
Introduced in 2.1.0. Unchanged from 6.7.7 through 7.1.0.
Signature, return type and hooks compared across 5 parsed releases.
$filesize value was added to the returned array.from the docblockAbout this page
- Parsed data
- Generated from the wordpress-develop 6.9.7 tag, from
src/wp-includes/post.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it. - Corrections
- Something wrong on this page? Report it and it gets fixed in the next regeneration.