首页 > 解决方案 > 将搜索结果页面更改为自定义帖子类型的单页

问题描述

我的网站中有两种搜索表单,一种用于blog posts,另一种用于products(woocommerce 产品)。我在这里想要的是我想在相关产品的单个页面中显示搜索结果,例如Blog Post搜索表单结果single-post.phpProduct搜索结果single-product.php

我已经使用隐藏的输入字段过滤了搜索,

<form action="<?php echo get_site_url() ?>" method="GET">
    <div class="input-group">
        <input type="search" name="s" class="form-control" placeholder="Search Products" required>
        <input type="hidden" name="post_type" value="products" />
        <div class="input-group-btn">
            <button class="btn btn-default" type="submit">
                 <i class="fa fa-search" aria-hidden="true"></i>
            </button>
        </div>
    </div>
</form>

如何将搜索结果定向到相关的单页?

标签: wordpresssearchwoocommercewordpress-theming

解决方案


您可以在 search.php 中添加这样的代码

 while ( have_posts() ) : the_post();
    if(isset($_GET['post_type'])) {
            $type = $_GET['post_type'];
            if($type == 'products') {
               get_template_part( 'single', 'product' );
            } else {
               get_template_part( 'single', 'post' );
            }
    } else {
            get_template_part( 'single', 'post' );
    }
    endwhile;

推荐阅读