Retrieves media attached to the passed post.
Parameters
Source
*
* @since 3.6.0
*
* @param string $type Mime type.
* @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
* @return WP_Post[] Array of media attached to the given post.
*/
function get_attached_media( $type, $post = 0 ) {
$post = get_post( $post );
if ( ! $post ) {
return array();
}
$args = array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'post_mime_type' => $type,
'posts_per_page' => -1,
'orderby' => 'menu_order',
'order' => 'ASC',
);
/**
* Filters arguments used to retrieve media attached to the given post.
*
* @since 3.6.0
*
* @param array $args Post query arguments.
* @param string $type Mime type of the desired media.
* @param WP_Post $post Post object.
*/
$args = apply_filters( 'get_attached_media_args', $args, $type, $post );
$children = get_children( $args );
/**
* Filters the list of media attached to the given post.
*
* @since 3.6.0
Changelog
Version | Description |
---|---|
3.6.0 | Introduced. |
You can get all attached media, regardless of type, by passing an empty string:
or
Important to note that this function only returns the attachments that were first uploaded/added to the post.
Uploading an image to Post A(ID 1) and then adding that image later to Post B(ID 2) would give an empty array if the following code was used:
$media = get_attached_media( 'image', 2 );
var_dump( $media );
You’d only get array data if you upload your media and add it to Post B before any other post.
It should be noted, that this function returns array of
WP_Post
objects, indexed by their ID, ordered by their “menu order” by default – that is where usually plugins handling attachment store their order positions…Examples
Get image attachment(s) to the current Post:
Get attachment(s) of mime-type ‘audio’ to the Post with an ID of 102: