WooCommerce店铺/归档页特定分类Add To Cart按钮文本修改问询
代码调整方案
你可以在原有代码基础上新增商品分类判断逻辑,使用WooCommerce原生has_term()函数即可实现需求,修改后的代码如下:
add_filter( 'woocommerce_loop_add_to_cart_link', 'replace_loop_add_to_cart_button', 10, 2 ); function replace_loop_add_to_cart_button( $button, $product ) { // 按商品分类匹配对应按钮文本 if ( has_term( 'cat1', 'product_cat', $product->get_id() ) ) { $button_text = __( "View Cat 1", "woocommerce" ); } elseif ( has_term( 'cat2', 'product_cat', $product->get_id() ) ) { $button_text = __( "View Cat 2", "woocommerce" ); } else { // 其他分类商品沿用默认文本 $button_text = __( "View Product", "woocommerce" ); } return '<a class="button" href="' . $product->get_permalink() . '">' . $button_text . '</a>'; }
注意事项
- 代码中的
cat1、cat2请替换为你站点实际的商品分类别名,如果你需要用分类ID、分类名称作为判断条件,只需修改has_term函数的第一个参数为对应的值即可 - 未归属到cat1、cat2的商品会默认显示原有
View Product文本,你可以根据需求自行调整else分支的文本内容
内容的提问来源于stack exchange,提问作者Om Agarwal
相关产品推荐
相关产品推荐

