WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need to extend standard WP search functionality so that the search term is also applied to files attached to a post. In other words if user types in "annual report" then search results would include all pages and posts which have this search string in content and also in attached filename?

My current code is:

$search_list = array();

$search_query['s'] = $_GET['find'];
$search_query['post_type'] = array('post', 'page');
$search_query['post_status'] = 'publish';
$search_query['posts_per_page'] = '2';
$search_query['paged'] = get_query_var('paged');
$search_query['nopaging'] = false;

$search = new WP_Query($search_query);

Many thanks.

share|improve this question
Just a thought, maybe you could look at the code for searching the media archive, hopefully that's well programmed. – Richard B May 17 '13 at 19:04

If you look at the $wpdb->posts table in the database, you will notice that the file names, minus the file type ending, are used for the post_title for attachments. This means that you can effectively search the file name if you can get your search function to search attachments, which the default search (almost) already does.

In your code, these two lines are working against you...

$search_query['post_type'] = array('post', 'page');
$search_query['post_status'] = 'publish';

... because attachments are 'post_type' == 'attachments' and 'post_status' == 'inherit'. If you alter the second of those to be ...

$search_query['post_status'] = array('publish','inherit);

... and leave off the first, you should have it working. That is...

$search_query['s'] = 'annual report';
$search_query['post_status'] = array('publish','inherit');
$search = new WP_Query($search_query);

You can also alter the global search with...

function search_attach_names_wpse_99832($qry) {
  if($qry->is_search()) {
share|improve this answer
Thank you for reply. I did get to the point of querying attachments, but how can I display parent post instead of the attachment post? The difficulty is that I need to filter out those results which come from the parent post content search. For example if I have phrase "annual accounts" both in attachments and post body then I want to display only one instance of parent post in search results. – lekso May 20 '13 at 8:44

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.