自定义帖子类型的自定义搜索不起作用



我为自定义帖子类型创建了一个自定义搜索功能。它以前工作得很好。现在搜索结果重定向到默认的WordPress搜索,并且没有得到定义的模板(archivesearch.php(

注意:这似乎是因为Wooccommerce的一些操作和过滤器

搜索结果模板的functions.php代码

// 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 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模板

<?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;
?>

如果有人面临同样的问题,那是由于Wooccommerce之间的操作钩子冲突。

我在WooCommerce中遇到了类似的问题,并使用"template_include"筛选器为自定义帖子类型有条件地调用自定义搜索模板。"add_filter"文档显示,可以设置优先级值以修改执行顺序。https://developer.wordpress.org/reference/functions/add_filter/

修改下面的代码以添加优先级值应该可以。

尝试从以下内容更改:

add_filter( 'template_include', 'template_chooser' );

到以下位置:

add_filter( 'template_include', 'template_chooser', 11 );

请确保使用大于10的值。

最新更新