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

WooCommerce店铺页按商品分类自定义替换加入购物车按钮文本

修改后的代码实现
// 移除店铺循环中的默认加购按钮
add_action( 'after_setup_theme', 'my_remove_add_to_cart', 99 );
function my_remove_add_to_cart() {
    // 仅在商品循环页面执行移除操作
    if ( is_shop() || is_product_category() ) {
        remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
    }
}

// 添加自定义分类对应文本的按钮
add_action( 'woocommerce_after_shop_loop_item', 'custom_view_product_button', 10 );
function custom_view_product_button() {
    // 仅在店铺/商品分类归档页面生效
    if ( ! ( is_shop() || is_product_category() ) ) {
        return;
    }

    global $product;
    if ( ! $product ) {
        return;
    }

    // 定义分类Slug与按钮文本的映射关系,请根据实际情况修改
    $category_button_texts = array(
        'category-1' => '查看系列1商品',
        'category-2' => '立即选购系列2',
        'category-3' => '了解系列3详情',
        'category-4' => '进入系列4专区',
        'category-5' => '查看系列5产品',
    );

    $button_text = 'View product'; // 默认文本
    $product_categories = get_the_terms( $product->get_id(), 'product_cat' );

    // 遍历商品所属分类,匹配对应的按钮文本
    if ( $product_categories && ! is_wp_error( $product_categories ) ) {
        foreach ( $product_categories as $category ) {
            if ( isset( $category_button_texts[ $category->slug ] ) ) {
                $button_text = $category_button_texts[ $category->slug ];
                break; // 匹配到第一个对应分类后停止遍历
            }
        }
    }

    $link = $product->get_permalink();
    echo '<a href="' . esc_url( $link ) . '" class="button addtocartbutton">' . esc_html( $button_text ) . '</a>';
}
关键说明
  • 页面生效范围控制:通过is_shop()和is_product_category()判断,确保代码仅在主店铺页面和商品分类归档页面执行,单个商品页不受影响,保留原有的"Add to cart"按钮。
  • 分类文本映射:在$category_button_texts数组中,将商品分类的Slug(可在WordPress后台商品分类编辑页查看)与你需要的按钮文本一一对应,按实际需求修改即可。
  • 安全处理:使用esc_url()和esc_html()对链接和文本进行转义,避免XSS安全风险。
  • 默认文本:如果商品不属于设置的5个分类,会使用默认的"View product"文本,你也可以修改这个默认值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 11:15:57