You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress自定义产品搜索URL后模板适配异常求助

Fix WooCommerce Product Search Template Not Loading After URL Rewrite

Hey there! Let's break down why your clean search URL isn't pulling up the WooCommerce product template. The core issue right now is that when you redirect to /search/holi/, you're losing the post_type=product parameter—this is what tells WordPress to load the product-specific search template instead of the default one.

Here's a proper fix that keeps your clean URL structure while ensuring the correct template loads:

Step 1: Add a Custom Rewrite Rule

First, we need to teach WordPress that URLs like /search/{keyword}/ should be treated as product searches. Add this code to your theme's functions.php file or a custom plugin:

// Map clean search URLs to product search queries
function wpb_add_product_search_rewrite_rule() {
    add_rewrite_rule(
        '^search/([^/]+)/?$',
        'index.php?s=$matches[1]&post_type=product',
        'top'
    );
}
add_action('init', 'wpb_add_product_search_rewrite_rule');

Step 2: Update the Redirect Function

Modify your existing redirect to only target product searches (so we don't break regular post searches) and point to our clean URL structure:

// Redirect dynamic product search URLs to clean slugs
function wpb_change_product_search_url() {
    // Only trigger for product-specific searches
    if (is_search() && !empty($_GET['s']) && isset($_GET['post_type']) && $_GET['post_type'] === 'product') {
        $search_term = urlencode(get_query_var('s'));
        wp_redirect(home_url("/search/{$search_term}/"));
        exit();
    }
}
add_action('template_redirect', 'wpb_change_product_search_url');

Step 3: Flush Rewrite Rules

To make the new rewrite rule active, you need to flush WordPress's rewrite rules:

  • Head to Settings > Permalinks in your WordPress dashboard
  • Click "Save Changes" (no need to edit anything—just saving will refresh the rules)

Why This Works

  • The rewrite rule maps your clean /search/holi/ URL to the underlying query ?s=holi&post_type=product, which tells WordPress to load the WooCommerce product search template.
  • The updated redirect only targets product searches, so regular content searches (without the post_type=product parameter) will still function normally.
  • If your theme has a custom product search template (like search-product.php), WooCommerce will automatically use it. If not, it'll fall back to the default WooCommerce product archive template adjusted for search results.

内容的提问来源于stack exchange,提问作者user2077431

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:16:09