If you’re experiencing slow queries in your WordPress media library due to a large database, you might find it helpful to optimize your search queries. In this article, we’ll guide you through a step-by-step process based on a user’s experience and the community’s suggestions.

1. Identify the Performance Issue:

The user reported slow queries in the media library, particularly when searching. The provided SQL query includes searching in the attachment file names, leading to performance problems.

2. Understand the Query:

The SQL query involves joining tables and searching for specific terms in the post title, excerpt, content, and attachment file names. The user seeks to exclude file name searches to enhance performance.

3. Consider Alternate Approaches:

A community member advises against directly manipulating SQL queries and suggests looking into API calls, specifically WP_Query parameters. This can provide a more actionable and efficient solution.

4. Explore WordPress Filters:

Another community member recommends using the wp_allow_query_attachment_by_filename filter, which controls whether attachment queries include filenames. However, the user encounters challenges due to other parts of WordPress core setting this filter to true.

5. Implement a Filter in Functions.php:

To address the issue, the community suggests adding a filter in the functions.php file to disable querying filenames. However, the user encounters difficulties as WordPress core turns the filter to true in specific files.

6. Alternative Solution Using posts_search Filter:

Considering the challenges with the previous filter, an alternative solution is proposed. Use the posts_search filter to modify the search query directly. This approach involves removing the part of the query related to filename searches.

Here’s an example of how to implement the posts_search filter:

function modify_attachment_search_query($search, $wp_query) {
    if (is_admin() && $wp_query->query['post_type'] == 'attachment' && isset($_GET['s'])) {
        $search = preg_replace("/(AND\s*\(.*?sq1.meta_value LIKE '.*?'\))/", '', $search);
    return $search;
add_filter('posts_search', 'modify_attachment_search_query', 10, 2);

7. Test and Backup:

Before implementing any changes, it’s crucial to test them in a staging environment. Additionally, make sure to back up your website to avoid data loss in case of unforeseen issues.

By following these steps, you can address slow queries in your WordPress media library and improve overall performance. Keep in mind that modifying core functionalities should be done with caution, and testing is essential.

Leave a Reply

Your email address will not be published. Required fields are marked *