The get_attached_media WordPress PHP filter allows you to filter the list of media attached to a specific post.
Usage
add_filter('get_attached_media', 'your_custom_function', 10, 3); function your_custom_function($children, $type, $post) { // Your custom code here return $children; }
Parameters
$children
(WP_Post[]): Array of media attached to the given post.$type
(string): Mime type of the media desired.$post
(WP_Post): Post object.
More information
See WordPress Developer Resources: get_attached_media
Examples
Filter Images Only
Filter only images from the attached media of a post.
add_filter('get_attached_media', 'filter_images_only', 10, 3); function filter_images_only($children, $type, $post) { if ($type === 'image') { return $children; } return array(); }
Exclude Specific Media ID
Exclude a specific media ID from the attached media list.
add_filter('get_attached_media', 'exclude_specific_media_id', 10, 3); function exclude_specific_media_id($children, $type, $post) { $exclude_id = 123; // The media ID to exclude return array_filter($children, function ($child) use ($exclude_id) { return $child->ID !== $exclude_id; }); }
Limit Number of Attached Media
Limit the number of media items returned.
add_filter('get_attached_media', 'limit_attached_media', 10, 3); function limit_attached_media($children, $type, $post) { $limit = 5; // Number of media items to return return array_slice($children, 0, $limit); }
Change Order of Attached Media
Change the order of attached media by a specific property.
add_filter('get_attached_media', 'change_order_of_attached_media', 10, 3); function change_order_of_attached_media($children, $type, $post) { usort($children, function ($a, $b) { return strcmp($a->post_title, $b->post_title); }); return $children; }
Add Custom Attributes to Attached Media
Add custom attributes to attached media objects.
add_filter('get_attached_media', 'add_custom_attributes_to_media', 10, 3); function add_custom_attributes_to_media($children, $type, $post) { foreach ($children as $child) { $child->custom_attribute = 'Custom Value'; } return $children; }