Using WordPress ‘get_attached_media_args’ PHP filter

The get_attached_media_args WordPress PHP filter allows you to modify the arguments used to retrieve media attached to a specific post.

Usage

add_filter('get_attached_media_args', 'your_function_name', 10, 3);

function your_function_name($args, $type, $post) {
    // your custom code here
    return $args;
}

Parameters

  • $args (array) – Post query arguments.
  • $type (string) – Mime type of the desired media.
  • $post (WP_Post) – Post object.

More information

See WordPress Developer Resources: get_attached_media_args

Examples

Modifying media order

Change the order of attached media to display them in ascending order by date.

add_filter('get_attached_media_args', 'change_media_order', 10, 3);

function change_media_order($args, $type, $post) {
    $args['orderby'] = 'date';
    $args['order'] = 'ASC';
    return $args;
}

Display only images

Retrieve only image attachments for a post.

add_filter('get_attached_media_args', 'only_images', 10, 3);

function only_images($args, $type, $post) {
    $args['post_mime_type'] = 'image';
    return $args;
}

Limit media count

Limit the number of media items displayed to 5.

add_filter('get_attached_media_args', 'limit_media_count', 10, 3);

function limit_media_count($args, $type, $post) {
    $args['posts_per_page'] = 5;
    return $args;
}

Exclude specific media IDs

Exclude specific media IDs (e.g., 10, 20, 30) from the attached media.

add_filter('get_attached_media_args', 'exclude_specific_media', 10, 3);

function exclude_specific_media($args, $type, $post) {
    $args['post__not_in'] = array(10, 20, 30);
    return $args;
}

Filter media by custom field

Display media items that have a specific custom field (e.g., ‘featured_image’).

add_filter('get_attached_media_args', 'filter_media_by_custom_field', 10, 3);

function filter_media_by_custom_field($args, $type, $post) {
    $args['meta_key'] = 'featured_image';
    return $args;
}