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

如何实现WooCommerce单产品分类点击直接跳转至商品页?

实现WooCommerce单商品分类直接跳转至商品详情页

由于WooCommerce原生未提供该功能,你可以通过自定义代码实现需求,以下是两种可靠方案:

方案一:通过子主题functions.php添加代码

建议使用子主题,避免主题更新导致代码丢失:

在子主题的functions.php文件末尾添加以下代码:

add_action('template_redirect', 'redirect_single_product_category');
function redirect_single_product_category() {
    // 仅在商品分类页触发逻辑
    if (is_product_category()) {
        global $wp_query;
        // 获取当前分类下的商品总数(包含子分类商品)
        $product_count = $wp_query->found_posts;
        
        if ($product_count === 1) {
            // 获取分类下的唯一商品
            $product = $wp_query->posts[0];
            // 跳转至商品详情页
            wp_redirect(get_permalink($product->ID));
            exit;
        }
    }
}

可选调整:排除子分类商品统计

如果希望仅统计当前分类直接关联的商品(不含子分类下的商品),替换为以下代码:

add_action('template_redirect', 'redirect_single_product_category');
function redirect_single_product_category() {
    if (is_product_category()) {
        $current_category = get_queried_object();
        
        // 查询当前分类直接关联的商品(不含子分类)
        $product_query = new WP_Query(array(
            'post_type' => 'product',
            'post_status' => 'publish',
            'tax_query' => array(
                array(
                    'taxonomy' => 'product_cat',
                    'field' => 'term_id',
                    'terms' => $current_category->term_id,
                    'include_children' => false
                )
            ),
            'posts_per_page' => -1
        ));
        
        $product_count = $product_query->found_posts;
        
        if ($product_count === 1) {
            $target_product = $product_query->posts[0];
            wp_redirect(get_permalink($target_product->ID));
            exit;
        }
    }
}

方案二:创建自定义插件(不受主题更新影响)

适合不希望修改主题文件的用户,步骤如下:

  1. 本地新建wc-single-category-redirect.php文件
  2. 复制以下代码到文件中:
<?php
/**
 * Plugin Name: WooCommerce Single Category Redirect
 * Description: 自动将仅含单个商品的分类页跳转至对应商品详情页
 * Version: 1.0
 * Author: Custom
 */

add_action('template_redirect', 'wc_scr_redirect_single_product_category');
function wc_scr_redirect_single_product_category() {
    if (is_product_category()) {
        global $wp_query;
        $product_count = $wp_query->found_posts;
        
        if ($product_count === 1) {
            $product = $wp_query->posts[0];
            wp_redirect(get_permalink($product->ID));
            exit;
        }
    }
}
  1. 将文件上传到站点wp-content/plugins/目录
  2. 后台「插件」列表中启用「WooCommerce Single Category Redirect」插件

注意事项

  • 修改前建议备份站点文件和数据库
  • 若需排除特定分类,可在if (is_product_category())后添加&& !is_product_category(array(12, 34))(12、34为目标分类ID)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 16:52:36