I created a custom search functionality for a custom post type. It works well before. Now search results redirects to the default WordPress search and do not get the defined template (archive-search.php).
Note: It seems this happens because of some Woocommerce actions and filters
functions.php
code for search result template
// Custom Search Template
function template_chooser($template)
{
global $wp_query;
$post_type = get_query_var('post_type');
if( $wp_query->is_search && $post_type == 'client' )
{
return locate_template('archive-search.php');
}
return $template;
}
add_filter('template_include', 'template_chooser');
form code
<form role="search" action="<?php echo site_url('/'); ?>" method="get">
<div class="mb-3">
<label for="company" class="form-label">Name</label>
<input type="text" name="s" class="form-control" />
</div>
<input type="hidden" name="post_type" value="book" />
<input type="submit" class="btn" value="Search" />
archive-search.php
template
<?php
$args = array(
'post_type' => 'book',
'posts_per_page' => 5,
's' => $_GET['s'],
'orderby' => 'date',
'order' => 'ASC',
);
$books = new WP_Query( $args );
if($books->have_posts()):
echo '<ul class="list-unstyled">';
while($books->have_posts()): $books->the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
endwhile;
echo '</ul>';
endif;
?>
2
Answers
If anyone facing the same issue, it is due to a conflict between Woocommerce action hook.
I had a similar issue with WooCommerce and using ‘template_include’ filter to call a custom search template conditionally for a custom post type. The ‘add_filter’ documentation shows that a priority value can be set in order to modify the execution order.
https://developer.wordpress.org/reference/functions/add_filter/
Modifying your code below to add a value for the priority should work.
Try to change from the below:
to the following:
Making sure to use a value higher than 10.