Media library search not working on Wordpress

We have Brandspace Pixelenity theme installed on a Wordpress web site. We also have some plugins installed (WPML, Wordpress SEO, Contact Form 7, Advanced Post Types Order…). And we had a situation when search in Media Library was not working. We didn’t know what was causing the problem, but we suspected it was the WPML plugin or the Brandspace Pixelenity theme.

After googling for some time and not finding anything that would point us in the right direction, we decided to try and change the theme to the basic Wordpress theme Twenty eleven. The media library search worked perfectly. So we were almost sure that the theme was causing the problem. The obvious thing would be to upgrade the theme to the latest version, but since we had to make to many changes to the original theme, that was not an option. Of course this is not the ideal case but we had to deal with the situation.

So we decided to debug the theme. First we logged all the sql queries that were triggered when we fired the search in the media library. Here comes the interesting part. SQL query behind the media library search did not include searching for 'attachment' post types but only looked for the posts of the type 'post'.

Example of the search query

SELECT * SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts JOIN wp_icl_translations t ON wp_posts.ID = t.element_id AND t.element_type IN ("post_post") JOIN wp_icl_languages l ON t.language_code=l.code AND l.active=1 WHERE 1=1 AND (((wp_posts.post_title LIKE "%search_string%") OR (wp_posts.post_content LIKE "%search_string%"))) AND wp_posts.post_type IN ("post") AND (wp_posts.post_status = "inherit" OR wp_posts.post_status = "private") AND t.language_code="en" ORDER BY wp_posts.menu_order, wp_posts.post_date DESC LIMIT 0, 20

After some hours spent on debugging we got to the source of the problem. In files PeThemeController.php and in PeThemeBrandspace.php there is a function

public function pre_get_posts_filter($query) {
    if ($query->is_search) {
        $query->set('post_type',array('post'));
    }
    return $query;
}

Why the post type is set only to post_type = ‘post’ we do not know but after we changed the line to

$query->set('post_type',array('post’,’attachment’));

the search library started to work. Now, why in such an advanced theme the basic Media Library Search would not be working is beyond our comprehension, but once you decide to use a theme you might be in for a lengthy debugging session, just to get some basic functionality working again.

You have been warned... :)