get_attached_media()
Retrieves media attached to the passed post.
Uses: get_children()
Hooks from the function
Return
WP_Post[]
. Array of media attached to the given post.
Usage
get_attached_media( $type, $post );
- $type(string) (required)
- Mime type.
- $post(int|WP_Post)
- Post ID or WP_Post object.
Default: global $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. |