I am working on search. I am able to search post by tag and category but not able to search by title and content.
I tried below code but it's not working. Would you help me out?
$getSearch = get_search_query();
//print($search);
$query = new WP_Query([
'post_type' => 'post',
'tax_query' => array(
'relation' => 'OR',
array(
's'=> $getSearch // for title and content
),
array(
'taxonomy' => 'post_tag', //for tag
'field' => 'slug',
'terms' => array($getSearch),
),
array(
'taxonomy' => 'category', // for category
'field' => 'slug',
'terms' => array($getSearch),
),
),
]);
if ($query->have_posts() ):
while ( $query->have_posts() ) {$query->the_post();?>
<!--some content-->
<?php }
else :
get_template_part( 'template-parts/content', 'none' );
endif;
?>
?>
function.php
add_action( 'pre_get_posts', 'my_search_exclude' );
function my_search_exclude( $query ) {
if ( ! $query->is_admin && $query->is_search && $query->is_main_query() ) {
$query->set( 'post_type', array( 'post', 'page', 'product' ) );
$query->set( 'post__not_in', array( 471 ) );
$taxquery= array(
'post_type' => 'any',
's'=> $query->get('s')
);
$query->set( 'tax_query', $taxquery);
}
}
tax_query
has a post_type and ans
value, this is extremely unusual and is not what the docs say goes in atax_query
. Thetax_query
parameter only has taxonomy related items in it, why have you put thes
andpost_type
parameters inside it? The docs never say to do this, and have examples that say otherwises
is just a generic search term parameter for the built in WP search, it's not a reusable generic field, you can't search taxonomy terms that way, thes
parameter only goes in a single place. See the official doc onWP_Query
for how to use the parameters developer.wordpress.org/reference/classes/wp_query/…, you can't just add ans
parameter to atax_query
to search tags/categories/etc, same goes formeta_query
, it's much more involved than that. If it's just search the post title and content, then use thes
parameter as documented