get_attached_media( string $type, int|WP_Post $post )

Retrieves media attached to the passed post.


Description Description


Parameters Parameters

$type

(string) (Required) Mime type.

$post

(int|WP_Post) (Optional) Post ID or WP_Post object. Default is global $post.


Top ↑

Return Return

(array) Found attachments.


Top ↑

Source Source

File: wp-includes/media.php

function get_attached_media( $type, $post = 0 ) {
	if ( ! $post = get_post( $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 mixed  $post Post ID or 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
	 *
	 * @param array  $children Associative array of media attached to the given post.
	 * @param string $type     Mime type of the media desired.
	 * @param mixed  $post     Post ID or object.
	 */
	return (array) apply_filters( 'get_attached_media', $children, $type, $post );
}

Top ↑

Changelog Changelog

Changelog
Version Description
3.6.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 2 content
    Contributed by Uriahs Victor

    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.

You must log in before being able to contribute a note or feedback.