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.
Opens WPIDE on
Code
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 add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.