Using WordPress ‘ajax_query_attachments_args’ PHP filter

The ajax_query_attachments_args WordPress filter allows you to modify the arguments passed to WP_Query during an Ajax call for querying attachments.

Usage

add_filter('ajax_query_attachments_args', 'my_custom_ajax_query_attachments_args', 10, 1);

function my_custom_ajax_query_attachments_args($query) {
    // your custom code here
    return $query;
}

Parameters

  • $query (array): An array of query variables that can be modified before passing to WP_Query.

More information

See WordPress Developer Resources: ajax_query_attachments_args

Examples

Exclude attachments with specific mime types

This example filters the query to exclude attachments with specific mime types.

add_filter('ajax_query_attachments_args', 'exclude_specific_mime_types', 10, 1);

function exclude_specific_mime_types($query) {
    $query['post_mime_type__not_in'] = array('image/png', 'image/jpeg');
    return $query;
}

Display only attachments uploaded by the current user

This example filters the query to show only attachments uploaded by the current user.

add_filter('ajax_query_attachments_args', 'display_current_user_attachments', 10, 1);

function display_current_user_attachments($query) {
    $current_user_id = get_current_user_id();
    $query['author'] = $current_user_id;
    return $query;
}

Limit attachment query results

This example limits the number of attachment results returned by the query.

add_filter('ajax_query_attachments_args', 'limit_attachment_query_results', 10, 1);

function limit_attachment_query_results($query) {
    $query['posts_per_page'] = 10;
    return $query;
}

Sort attachments by title in ascending order

This example sorts attachments by title in ascending order.

add_filter('ajax_query_attachments_args', 'sort_attachments_by_title', 10, 1);

function sort_attachments_by_title($query) {
    $query['orderby'] = 'title';
    $query['order'] = 'ASC';
    return $query;
}

Filter attachments by a custom meta key and value

This example filters attachments based on a custom meta key and value.

add_filter('ajax_query_attachments_args', 'filter_attachments_by_custom_meta', 10, 1);

function filter_attachments_by_custom_meta($query) {
    $query['meta_key'] = 'my_custom_meta_key';
    $query['meta_value'] = 'my_custom_value';
    return $query;
}