How to search for media by category

In order to be able to search for media attachments by category, first you have to enable category taxonomy for media attachments. Once you’ve enabled that you can use the following function to search for all media attachments, assigned to this category slug:

function getMediaByCategorySlug($categorySlug)
{
    $args = array( 
        'numberposts' => -1, 
        'category_name' => $categorySlug,
        'post_type' => 'attachment'
    );
    return get_posts( $args );
}
You can download the code for this how-to in
About Pavel Petrov 2 Articles |  21 How-tos
Pavel is a senior developer for the last 7 years, with extended interest in Linux administration, WordPress and Symfony.