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

如何修改WooCommerce代码,让购物车价格后也显示自定义文本

解决WooCommerce购物车价格后显示自定义文本的问题

你的代码已经尝试添加了woocommerce_cart_item_price钩子,但问题出在函数里获取自定义字段的方式——在购物车场景中,全局的$post和$product不一定能正确指向当前购物车项的产品,导致拿不到自定义文本。

修改后的完整代码

// 添加产品后台自定义字段
add_action('woocommerce_product_options_general_product_data', function() {
    woocommerce_wp_text_input([
            'id' => '_custom_text_after_price',
            'label' => __('价格后缀文本: ', 'themedomain'),
    ]);
});

// 保存自定义字段值
add_action('woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save');
function woocommerce_product_custom_fields_save($post_id)
{
    $custom_text = $_POST['_custom_text_after_price'];
    if (!empty($custom_text)) {
        update_post_meta($post_id, '_custom_text_after_price', esc_attr($custom_text));
    } else {
        // 清空空值,避免冗余数据
        delete_post_meta($post_id, '_custom_text_after_price');
    }
}

// 价格后缀文本显示逻辑
function cw_change_product_price_display( $price, $cart_item = null ) {
    // 初始化自定义文本
    $text = '';

    // 处理产品存档/详情页(woocommerce_get_price_html钩子)
    if (is_null($cart_item)) {
        global $product;
        if (isset($product) && $product->get_id()) {
            $text = get_post_meta( $product->get_id(), '_custom_text_after_price', true );
        }
    } 
    // 处理购物车页(woocommerce_cart_item_price钩子)
    else {
        $product_id = $cart_item['product_id'];
        $text = get_post_meta( $product_id, '_custom_text_after_price', true );
    }

    // 只有当文本不为空时才添加后缀
    if (!empty($text)) {
        $price .= ' /' . $text;
    }

    return $price;
}

add_filter( 'woocommerce_get_price_html', 'cw_change_product_price_display' );
add_filter( 'woocommerce_cart_item_price', 'cw_change_product_price_display', 10, 2 );

关键改动说明

  1. 兼容钩子参数差异:

    • woocommerce_get_price_html只传递$price参数,而woocommerce_cart_item_price会传递$price和$cart_item两个参数,所以给函数添加了可选的$cart_item参数,并通过判断该参数是否为空来区分场景。
  2. 正确获取产品ID:

    • 产品页面:通过全局$product对象的get_id()方法获取产品ID,比依赖$post->ID更可靠。
    • 购物车页面:从$cart_item['product_id']直接提取当前购物车项的产品ID,确保能拿到对应的自定义字段值。
  3. 优化空值处理:

    • 保存字段时,若用户清空输入,会删除对应的元数据,避免无效的空值存储。
    • 显示逻辑中只有当自定义文本不为空时才添加后缀,防止出现多余的 /符号。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 13:34:59