get_attached_media()
Gets attachments (images, videos, audio) attached to a post. Retrieves data objects in the form of an array.
This function returns only those attachments that were uploaded for the post (that are attached to the post).
For example, we uploaded an image to post A (ID 1), and then added this image to the content of post B (ID 2). Then, the following code will return an empty array:
$media = get_attached_media( 'image', 2 ); var_dump( $media );
WP_Post objects in the array returned by the function will be ordered in descending (ASC) order by the field menu_order.
Hooks from the function
Returns
WP_Post[]. Array of objects found attachments or an empty array: array()
Usage
$attach = get_attached_media( $type, $post );
- $type(string) (required)
- Type of attachments to retrieve. For example: 'image', 'audio', 'video', 'video/mp4'.
- $post(number/WP_Post)
- ID of the post whose attachment needs to be retrieved.
Default: current post
Examples
#1 Get the attachments (images) of the current post
In this example we will get the data of images attached to posts with ID=2018:
$media = get_attached_media( 'image', 2018 ); print_r( $media );
This code will display something like this:
Array ( [2024] => WP_Post Object ( [ID] => 2024 [post_author] => 1 [post_date] => 2013-01-09 19:46:33 [post_date_gmt] => 2013-01-09 15:46:33 [post_content] => [post_title] => ajax in WordPress [post_excerpt] => [post_status] => inherit [comment_status] => open [ping_status] => open [post_password] => [post_name] => ajax-in-wp [to_ping] => [pinged] => [post_modified] => 2013-01-09 19:46:33 [post_modified_gmt] => 2013-01-09 15:46:33 [post_content_filtered] => [post_parent] => 2018 [guid] => http://wp-kama.com/wp-content/uploads/2013/01/ajax-in-wp.jpg [menu_order] => 0 [post_type] => attachment [post_mime_type] => image/jpeg [comment_count] => 0 [filter] => raw ) [2000] => WP_Post Object ( [ID] => 2024 ... ) )
#2 Get the first image attached to the post
This code shows how to get the first image attached to a post with ID = 2018:
$media = get_attached_media( 'image', 2018 ); $media = array_shift( $media ); // picture link $image_url = $media->guid; // display the picture in the browser echo '<img src="'. $image_url .'" />';
#3 Get post attachments of any type
You can get all the attachments of a post, regardless of type. To do this, you need to specify an empty string in the first parameter:
$media = get_attached_media( '' ); // or $media = get_attached_media( '', 102 );
Changelog
| Since 3.6.0 | Introduced. |