How to change query search in wordpress?

Member

by addison , in category: PHP CMS , 8 months ago

How to change query search in wordpress?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , 8 months ago

@addison 

To change the query search in WordPress, you can modify the search query using the pre_get_posts hook. Follow these steps:

  1. Open your theme's functions.php file. This file is located in wp-content/themes/your-theme-name/functions.php.
  2. Add the following code snippet to the functions.php file:
1
2
3
4
5
6
7
8
function custom_search_filter($query) {
    if ($query->is_search && !is_admin()) {
        // Modify the search query here
        $query->set('post_type', 'post'); // Change post_type to the desired post type
    }
    return $query;
}
add_filter('pre_get_posts','custom_search_filter');


  1. Modify the search query as needed in the custom_search_filter function. In the example code above, we changed the post type to 'post'. You can modify other parameters such as post status, category, tags, etc.
  2. Save the functions.php file and refresh your website to see the changes take effect.


By using the pre_get_posts hook, you can customize the search query to suit your needs in WordPress.