Using WordPress ‘get_attached_media()’ PHP function

The get_attached_media() WordPress PHP function retrieves media attached to a specified post.

Usage

To use the function, provide the mime type and an optional post ID or WP_Post object:

get_attached_media('image', 123);

Parameters

  • $type (string) – Required. Mime type of the media to retrieve.
  • $post (int|WP_Post) – Optional. Post ID or WP_Post object. Default is the global $post.

More information

See WordPress Developer Resources: get_attached_media()

This function returns an array of WP_Post objects, indexed by their ID, ordered by their “menu order” by default.

Examples

Get image attachments for the current post

This code snippet retrieves all image attachments for the current post:

$images = get_attached_media('image');

Get audio attachments for a specific post

This code snippet retrieves all audio attachments for the post with an ID of 102:

$audios = get_attached_media('audio', 102);

Get all attached media for the current post

This code snippet retrieves all attached media for the current post, regardless of mime type:

$all_media = get_attached_media('');

Get all attached media for a specific post

This code snippet retrieves all attached media for the post with an ID of 102, regardless of mime type:

$all_media = get_attached_media('', 102);

Get video attachments for a specific post

This code snippet retrieves all video attachments for the post with an ID of 99:

$videos = get_attached_media('video', 99);