wp_get_attachment_metadata()
Retrieve attachment meta field for attachment ID.
Uses: get_post_meta()
Used By: wp_maybe_generate_attachment_metadata(), wp_get_original_image_path(), image_get_intermediate_size()
1 time — 0.000745 sec (slow) | 50000 times — 1.22 sec (fast) | PHP 7.0.8, WP 4.6
Hooks from the function
Return
Array|false
. Attachment metadata. False on failure.
Usage
wp_get_attachment_metadata( $attachment_id, $unfiltered );
- $attachment_id(int)
- Attachment post ID.
Default: global $post - $unfiltered(true|false)
- If true, filters are not run.
Default: false
Examples
#1 Get the metadata of attachment 656 (picture):
$array = wp_get_attachment_metadata( 656 );
As a result, the variable $array
will contain approximately the following data (depending on the attachment type):
Array ( [width] => 356 [height] => 299 [file] => 2011/05/dinamic-archives.png [sizes] => Array ( [thumbnail] => Array ( [file] => dinamic-archives-80x80.png [width] => 80 [height] => 80 [mime-type] => image/png ) [medium] => Array ( [file] => dinamic-archives-120x100.png [width] => 120 [height] => 100 [mime-type] => image/png ) ) [image_meta] => Array ( [aperture] => 0 [credit] => [camera] => [caption] => [created_timestamp] => 0 [copyright] => [focal_length] => 0 [iso] => 0 [shutter_speed] => 0 [title] => ) )
Let's bring up the sizes of the image:
$meta = wp_get_attachment_metadata( 656 ); if( $meta ){ echo $meta['width'] .'x'. $meta['height']; //> 356х299 }
#2 Get the metadata of attachment 95 (video):
$array = wp_get_attachment_metadata( 95 );
As a result, the variable $array
will contain approximately the following data (depending on the attachment type):
Array ( [filesize] => 61429114 [mime_type] => video/mp4 [length] => 1375 [length_formatted] => 22:55 [width] => 1280 [height] => 720 [fileformat] => mp4 [dataformat] => quicktime [audio] => Array ( [dataformat] => mp4 [codec] => ISO/IEC 14496-3 AAC [sample_rate] => 44100 [channels] => 2 [bits_per_sample] => 16 [lossless] => [channelmode] => stereo ) [created_timestamp] => 1538981268 )
#3 Get full URL to uploaded image file
NOTE that when calling wp_get_attachment_metadata(), the ARRAY index returned from file
is the file path relative to wp-content/uploads
.
If you want to get url of domain to link up, you can use snippet below
$attachment_metadata = wp_get_attachment_metadata( $attachment_id ); $upload_url = wp_upload_dir()['url']; $file_rel_path = $attachment_metadata['sizes']['medium_large']['file']; echo "{$upload_url}/{$file_rel_path}";
Changelog
Since 2.1.0 | Introduced. |
Since 6.0.0 | The $filesize value was added to the returned array. |