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

如何在WooCommerce加入购物车提示中用product_sku替换product_name

实现方法

你原有代码的问题是逻辑里仅读取了产品标题作为展示内容,只需要修改循环内的取值逻辑,替换为读取产品SKU即可,修改后的可用代码如下:

add_filter ( 'wc_add_to_cart_message_html', 'wc_add_to_cart_message_custom', 10, 2 );

function wc_add_to_cart_message_custom( $message, $products ) {
    if ( empty( $products ) ) {
        return $message;
    }

    foreach( $products as $product_id => $qty ) {
        $product = wc_get_product( $product_id );
        // 优先取SKU,没有SKU的话兜底显示产品名称避免空白
        $show_content = $product->get_sku() ? $product->get_sku() : get_the_title( $product_id );
        $titles[] = $show_content;
    }

    $titles = array_filter( $titles );
    $added_text = sprintf( _n( 'product %s', 'product %s', sizeof( $titles ), 'woocommerce' ), wc_format_list_of_items( $titles ) );
    $message = sprintf( '%s <img src="images/Success.svg" style="width: 24px"> <a style="font-weight: 800">Added: </a>%s', esc_html__( '', 'woocommerce' ), esc_html( $added_text ));

    return $message;
}

核心修改说明

  • 遍历产品ID时,先通过wc_get_product()实例化WooCommerce产品对象
  • 调用产品对象的get_sku()方法获取SKU值,替换原有的产品标题读取逻辑
  • 新增了空SKU兜底逻辑,兼容未设置SKU的产品场景

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

相关产品推荐
方舟 Agent Plan

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

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