Search not working with title and content

Edit: It appears your actual problem is searching tags and categories, hence placing the s parameter inside the tax_query.

There is no way to search tags categories and other terms using only the fields provided by WP_Query. Your query doesn’t work because what you want isn’t possible with just the parameters available.

Instead of asking how to fix your solution/attempt, I’d recommend asking a new question for how to search taxonomy terms/categories/tags


Original answer:

The reason your search doesn’t work, is because your query has no search:

$query = new WP_Query([
  'post_type' => 'post',
  'tax_query' => array(
    'relation' => 'OR',
       array(
      's'=> $getSearch // for title and content
    ),
...

For some reason, the s parameter has been inserted inside the tax_query, which doesn’t make a lot of sense.

For example, here is a normal query that searches:

$query = new WP_Query([
  's' => 'search terms',
etc..

But for some reason you’ve put it inside the tax_query:

$query = new WP_Query([
  'tax_query' => array(
    'relation' => 'OR',
       array(
          's'=> $getSearch // for title and content
       ),

This will not work, and is not what the documentation and examples suggest.

What’s more, the code is creating a brand new query unnecessarily, which also doesn’t make sense as it doubles the page loading time, and breaks pagination.

Instead, all these issues can be bypassed trivially by using the pre_get_posts filter, e.g. in functions.php:

add_action( 'pre_get_posts', function( \WP_Query $q ) {
    if ( !$q->is_main_query() || !$q->is_search() ) {
        return;
    }
    $q->set( 'tax_query', ....... );
} );

Now you can use search.php as intended, with a standard post loop, and everything would work as it normally does. No need for a query at the top of the file.

The TLDR: If you want to change the posts WP shows, tell WP what you want via pre_get_posts. Don’t create a second query, it cripples performance and introduces lots of new problems

Leave a Comment