skip to Main Content

I have a heavy site with over 200,000 articles
When searching in WordPress, this search looks for the desired word in the title, content, and excerpt
In this number of articles, the result of slow query is more than 50 seconds and slows down MariaDB

I want to write a filter to limit this query to only titles

I think this slow query will be fixed and the problem will be solved
Please help to write this filter or help if you know that the problem can be solved by another solution
Thank you

in the file
wp-includes/class-wp-query.php

2

Answers


  1. Can you please try this code and let me know if it work’s.

    function limit_search_to_titles($query) {
    if ($query->is_search && !is_admin()) {
        $query->set('post_type', 'post'); // Adjust 'post' to match your custom post types if needed
        $query->set('posts_per_page', -1); // Include all results, you can limit this if necessary
        $query->set('s', ''); // Clear the search term
        $query->set('title', $query->query_vars['s']); // Set the title to the search term
    } } add_action('pre_get_posts', 'limit_search_to_titles');
    
    Login or Signup to reply.
  2. You can use this one

    function custom_search_query( $query ) {
        if ( $query->is_search && ! is_admin() ) {
            
            $query->set( 'post_type', 'post' ); 
            $query->set( 'posts_per_page', -1 );
            $query->set( 's', get_query_var( 's' ) ); 
    
            // Modify the search query to search only in post titles.
            $query->set( 'title', true );
        }
    }
    add_action( 'pre_get_posts', 'custom_search_query' );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search