My 3rd plugin – Media Search Enhanced is to solve an issue in a client’s project (again!). In this project, the client uploads tremendous images to the Media Library and later they reported a search bug.
When they searched the Media Library, some images showed up in the search results, but some didn’t. When I took a deeper look into this, I found the keyword search seemed to skip the Caption and Alternative Text fields. If the keyword is in these 2 fields, the image will not be included in the search results.
It’s actually not a bug, the way WordPress does the search leads to it. In a default WordPress search, which means query posts with the variable “s”, it only search for “post_title” and “post_content” in the posts table.
So I tracked down to figure out where all data in the Media fields are saved to. And here is data mapping:
- Title – post_title in the posts table
- Caption – post_excerpt in the posts table
- Alternative Text – meta_value in the postmeta table, the meta_key is “_wp_attachment_image_alt”
- Description – post_content in the posts table
To include post_excerpt and a certain meta_value in the search fields, the best chance is to use the “post_clauses“, or these clause-specific filters:
So in Media Search Enhanced, I use 3 functions to hook to the filters above, and am going to add more features to it soon:
- TODO – Search media file name.
- TODO – Add result snippet column which shows text snippets around found keyword on the Media Library screen.
- TODO – Search Media Categories, Tags or Custom Taxonomies.
One thing I’d like to note is, WP_Query could take lots of parameters to do the posts query, but the “s” can’t be used with “meta_query” at the same time, because when doing so, the WHERE statement in the SQL would be like:
” AND ( ( wp_posts.post_title LIKE ‘%keyword%’) OR ( wp_posts.post_content LIKE ‘%keyword%’) ) AND ( wp_postmeta.meta_key = ‘_wp_attachment_image_alt’ AND wp_postmeta.meta_value LIKE ‘%” . $vars[‘s’] . “%’ )“
Which prevent the posts being found for the WHERE statement is much unlikely to sustained.
Here are 2 screenshots to demo the Media Library search results after installing Media Search Enhanced. It just a simple plugin but should fix an issue lots WP users ever experienced.
I’m a senior web developer helping clients build their websites to grow businesses. Currently I’m based in Taipei, Taiwan.
I write things about WordPress, AngularJS and life. Whenever you’d like to find someone to talk about these topics, just get in touch!