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

WooCommerce开发:如何在分类URL中添加父分类路径

问题原因

手动拼接分类URL的逻辑存在缺陷:直接通过$term->slug拼接地址仅能获取当前分类的单独别名,不会自动追溯拼接父级分类的路径层级;同时硬编码/product-category/路径的写法,在自定义产品分类固定链接前缀的场景下还会触发链接404问题。

修复方法

放弃手动拼接分类链接,改用WordPress原生函数get_term_link()获取分类归档地址,该函数会自动完成父级路径拼接、自定义固定结构匹配逻辑,从根源上避免路径缺失问题。

修正后的完整可运行代码:

remove_action( 'woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title', 10 );
add_action( 'woocommerce_shop_loop_item_title', 'VS_woo_loop_product_title', 10 );
 
function VS_woo_loop_product_title() {
    echo '<h3>' . get_the_title() . '</h3>';
    global $post;
    $terms = get_the_terms( $post->ID, 'product_cat' );
    if ( $terms && ! is_wp_error( $terms ) ) :
        $cat_links = array();
        foreach ( $terms as $term ) {
            // 原生方法获取分类链接,自动包含完整父分类路径
            $term_link = get_term_link( $term, 'product_cat' );
            if( !is_wp_error($term_link) ){
                $cat_links[] = '<a href="'.esc_url( $term_link ).'">'.$term->name.'</a>';
            }
        }
        $on_cat = join( ", ", $cat_links );
    ?>
    <div class="label-group">
        <div class="categories-link"><?php echo $on_cat; ?></div>
    </div>
<?php endif;
}
附带优化项
  • 补全全局$post对象声明,避免部分主题/插件环境下$post->ID调用报错
  • 新增get_term_link()返回结果的错误判断,避免个别异常分类导致前台页面报错
  • 移除硬编码的分类固定前缀,适配所有自定义固定链接设置场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 01:03:36