# Search Media by Alt Text Too

> Makes the Media Library search, in both the grid and list views and the media picker, also match images by their alt text, which often describes the image better than the file name.

- Type: PHP
- Runs: Admin only
- Category: [Media](https://wpide.com/library/category/media/)
- Tags: media-library, search, alt-text
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/media-search-alt-text/

## Code

```php
add_filter( 'posts_search', function ( $search, $query ) {
    global $wpdb, $pagenow;

    $is_media_screen = 'upload.php' === $pagenow || ( wp_doing_ajax() && isset( $_REQUEST['action'] ) && 'query-attachments' === $_REQUEST['action'] );
    if ( ! is_admin() || '' === $search || ! $is_media_screen || 'attachment' !== $query->get( 'post_type' ) ) {
        return $search;
    }

    $term = trim( (string) $query->get( 's' ) );
    if ( '' === $term ) {
        return $search;
    }

    $match = $wpdb->prepare(
        "{$wpdb->posts}.ID IN ( SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_wp_attachment_image_alt' AND meta_value LIKE %s )",
        '%' . $wpdb->esc_like( $term ) . '%'
    );

    return preg_replace( '/^\s*AND\s*/', ' AND ( ( ', $search, 1 ) . " ) OR $match )";
}, 10, 2 );
```

## Notes

Only adds matches; normal title, caption and file name searches keep working.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Search Media by Alt Text Too" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
