WordPress include tags, categories and taxonomies in search results

Posted on by Chandan

Many times we need to search by associated tags, category or custom taxonomy names . But WordPress doesn’t provide these by default. Therefore, we need to make our own results page which include the default search including tags, categories and custom taxonomy names. In this article, we learn a technique or a guideline to tackle these terms and show the matching posts if they have these. 

For example, If you have ‘mytag’ in some of your posts and you want to perform_search on ‘mytag’ the result should show that post.

First of all  if your theme doesn’t have search.php, then just add this file in your activated theme. This file is used to show the results.

WordPress include tags, categories and taxonomies in search results

In our Example, we will use the wordpress default theme twenty nineteen and modify search.php to get the desired results. This theme doesn’t include tags and categories for matching the keyphrase . We change everything on search.php file.

Basic Idea behind our code example:

  1. Remove the old query in the search.php file.
  2. get all the category, tag and custom taxonomy in array format. And loop every array and find matching name in these arrays. Then store the ids of the matched name in a separate array. 
  3. Using wp_query, query all the posts (by tax query )with these matched ids. Then store the resulting post_ids in an array.
  4. Now perform a default search_query and store all the ids in an array. 
  5. Now we have got two arrays of  ids which is the result. 
  6. Combine these two and remove duplicates. 
  7. Now we will perform a last query and show all the posts (by post__in parameter of wp_query) .  

 

<?php
/**
* The template for displaying search results pages
*
* @link https://developer.wordpress.org/themes/basics/template-hierarchy/#search-result
*
* @package WordPress
* @subpackage Twenty_Nineteen
* @since 1.0.0
*/
get_header();
?>
<section id="primary" class="content-area">
<main id="main" class="site-main">
<header class="page-header">
<h1 class="page-title">
<?php _e( 'Search results for:', 'twentynineteen' ); ?>
</h1>
<div class="page-description"><?php echo get_search_query(); ?></div>
</header><!-- .page-header -->
<?php
$search=get_search_query();
$all_categories = get_terms( array('taxonomy' => 'category','hide_empty' => true) );
$all_tags = get_terms( array('taxonomy' => 'post_tag','hide_empty' => true) );
//if you have any custom taxonomy
$all_custom_taxonomy = get_terms( array('taxonomy' => 'your-taxonomy-slug','hide_empty' => true) );

$mcat=array();
$mtag=array();
$mcustom_taxonomy=array();

foreach($all_categories as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mcat,$all->term_id);
}
}

foreach($all_tags as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mtag,$all->term_id);
}
}

foreach($all_custom_taxonomy as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mcustom_taxonomy,$all->term_id);
}
}

$matched_posts=array();
$args1= array(
'post_status' => 'publish',
'posts_per_page' => -1,
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $mcat
),
array(
'taxonomy' => 'post_tag',
'field' => 'term_id',
'terms' => $mtag
),
array(
'taxonomy' => 'custom_taxonomy',
'field' => 'term_id',
'terms' => $mcustom_taxonomy
)
)
);

$the_query = new WP_Query( $args1 );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
array_push($matched_posts,get_the_id());
//echo '<li>' . get_the_id() . '</li>';
}
wp_reset_postdata();
} else {

}

?>
<?php
// now we will do the normal wordpress search
$query2 = new WP_Query( array( 's' => $search,'posts_per_page' => -1 ) );
if ( $query2->have_posts() ) {
while ( $query2->have_posts() ) {
$query2->the_post();
array_push($matched_posts,get_the_id());
}
wp_reset_postdata();
} else {

}
$matched_posts= array_unique($matched_posts);
$matched_posts=array_values(array_filter($matched_posts));
//print_r($matched_posts);
?>

<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query3 = new WP_Query( array( 'post_type'=>'any','post__in' => $matched_posts ,'paged' => $paged) );
if ( $query3->have_posts() ) {
while ( $query3->have_posts() ) {
$query3->the_post();
get_template_part( 'template-parts/content/content', 'excerpt' );
}
twentynineteen_the_posts_navigation();
wp_reset_postdata();
} else {

}
?>
</main><!-- #main -->
</section><!-- #primary -->

<?php
get_footer();

 

WP Resources :

Similar article based on searching attachment images with ajax 

There are some plugins available to do this but doing this custom is very helpful to modify thing. Therefore we are doing this without using a plugin.

About Chandan

Author View all posts by Chandan →

5 Responses to WordPress include tags, categories and taxonomies in search results

  • […] WordPress include tags, categories and taxonomies in search results […]

  • Taofeek Oladiran Folami says:

    Beautiful post. Thank you. I am building my first wordpress website for a client which is heavy on transactions and raw computations rather than posts. This post has solved a lot of my headaches in trying to develop searches that are reasonably precise. I also gained more insight into the way wordpress works. Please understand, i am from the fortran, C, visual basic, visual basic for applications tradition, so there is the obvious dissidence in grasping web applications development. Thank you again.

  • Taofeek Oladiran Folami says:

    I have implemented the code snippet above. To make it work, i had to weak it a little. Two issues i resolved to make it work
    1′. if (strpos($par, $search) !== false) {} fails to add the term into the relevant array.
    my solution: if ($search == $par) {}, and it worked
    2. If $matchedposts is an empty array, the query, ” $query3 = new WP_Query( array( ‘post_type’=>’any’,’post__in’ => $matched_posts ,’paged’ => $paged) );” gives unexpected results. It actually fetched posts. My solution; tested that $matchedposts is not empty before invoking WP_Query. I empty, pass in an empty arguments array. if (! empty($matched_posts)) {
    $query3 = new WP_Query( array( ‘post_type’=>’any’,
    ‘post__in’ => $matched_posts ,
    ‘paged’ => $paged) );
    } else {
    $args = ”;
    $query3 = new WP_Query($args);
    }

    . Works like a charm.

    Hope this note helps.

  • Isa says:

    Did anyone actually get this to work? For me the search result shows post not matching the search query

  • Yosi Krivo says:

    Hello,

    I wonder if you could help me, I tried to replace the above code with the original cone in search.php but is didn’t work.

    I just nedd to add to my original search the followings:
    1. show count results.
    2. show serach terms.
    I would apprecite of you could send me the code for that.
    Many Thanks

  • Leave a Reply

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

    *

    *