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

WooCommerce移动端购物车:将价格及小计移至商品名称下方

我来帮你解决这个问题,你之前的代码主要有两个核心问题:一是钩子woocommerce_after_cart_item_name的参数使用错误,二是没有正确获取商品的动态价格和小计。下面是完整的解决方案,包含正确的钩子实现、价格/小计的动态获取,以及移动端的显示控制逻辑:

第一步:修正钩子函数,动态获取价格和小计

add_filter('woocommerce_after_cart_item_name', 'copy_cart_product_price_for_mobile', 10, 3);
function copy_cart_product_price_for_mobile($item_name, $cart_item, $cart_item_key) {
    // 获取当前商品对象
    $_product = apply_filters('woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key);
    
    // 确保商品对象有效
    if (!$_product) {
        return $item_name;
    }
    
    // 获取商品单价(应用官方过滤器,保证价格格式/自定义逻辑生效)
    $product_price = apply_filters('woocommerce_cart_item_price', WC()->cart->get_product_price($_product), $cart_item, $cart_item_key);
    
    // 初始化小计HTML为空
    $subtotal_html = '';
    
    // 当商品数量≥2时,才生成小计内容
    if ($cart_item['quantity'] >= 2) {
        $product_subtotal = apply_filters('woocommerce_cart_item_subtotal', WC()->cart->get_product_subtotal($_product, $cart_item['quantity']), $cart_item, $cart_item_key);
        $subtotal_html = '<p class="cart-subtotal-mobile">' . __('Subtotal:', 'woocommerce') . ' ' . $product_subtotal . '</p>';
    }
    
    // 构建移动端专属的价格容器,添加桌面端隐藏类
    $mobile_price_html = '<div class="cart-price-mobile-container">
        <p class="cart-price-mobile">' . __('Price:', 'woocommerce') . ' ' . $product_price . '</p>' .
        $subtotal_html . '</div>';
    
    // 将移动端内容追加到商品名称后
    return $item_name . $mobile_price_html;
}

关键修正点说明:

  • 修正了钩子参数:woocommerce_after_cart_item_name的第一个参数是$item_name(商品名称),而非你之前写的$cart_item,参数顺序错误会导致内容无法正确追加。
  • 用官方方法动态获取价格/小计:调用get_product_price和get_product_subtotal并应用对应过滤器,确保价格会自动适配折扣、税费等自定义规则,而非硬写固定数值。
  • 加入数量判断逻辑:只有当商品数量≥2时,才显示小计内容。

第二步:添加CSS控制显示隐藏

通过CSS实现移动端和桌面端的显示切换:

/* 桌面端默认隐藏移动端专属价格容器 */
.cart-price-mobile-container {
    display: none;
}

/* 移动端适配规则(可根据你的需求调整屏幕宽度阈值) */
@media (max-width: 768px) {
    /* 隐藏原生的价格和小计单元格 */
    .woocommerce-cart-form__cart-item .product-price,
    .woocommerce-cart-form__cart-item .product-subtotal {
        display: none;
    }
    
    /* 显示移动端专属的价格和小计 */
    .cart-price-mobile-container {
        display: block;
        margin-top: 8px;
        font-size: 0.9em;
        color: #666;
    }
    
    .cart-price-mobile, .cart-subtotal-mobile {
        margin: 4px 0;
    }
}

CSS逻辑说明:

  • 桌面端:隐藏我们追加的移动端价格容器,保留原生的价格/小计单元格布局。
  • 移动端:隐藏原生的价格和小计列,同时显示追加在商品名称下方的价格(及满足条件的小计)。

第三步:验证效果

  1. 将PHP代码添加到主题的functions.php文件,或者使用自定义代码插件(比如Code Snippets)。
  2. 将CSS代码添加到主题的自定义CSS区域,或者子主题的style.css文件。
  3. 测试购物车页面:
    • 桌面端:保持原有布局,看不到移动端专属内容。
    • 移动端:商品名称下方显示单价,当商品数量≥2时,额外显示小计,原生的价格/小计列被隐藏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 22:32:57