在WooCommerce购物车表格中添加折扣百分比列求助
在WooCommerce购物车表格中添加折扣百分比列
你当前用于产品页显示折扣百分比的代码(已翻译注释)可以继续保留:
////__________________________________________________________________________________________//// // 为批发价添加折扣百分比 // 仅适用于WooCommerce 3.0+版本 add_filter( 'woocommerce_format_sale_price', 'woocommerce_custom_sales_price', 10, 3 ); function woocommerce_custom_sales_price( $price, $regular_price, $sale_price ) { $percentage = round( ( $regular_price - $sale_price ) / $regular_price * 100 ).'%'; $percentage_txt = ' ' . __(' (-', 'woocommerce' ) . $percentage . __(' )', 'woocommerce' ); $price = '<del>' . ( is_numeric( $regular_price ) ? wc_price( $regular_price ) : $regular_price ) . '</del> <ins>' . ( is_numeric( $sale_price ) ? wc_price( $sale_price ) . $percentage_txt : $sale_price . $percentage_txt ) . '</ins>'; return $price; }
以下是为购物车表格添加折扣百分比列的代码:
1. 添加购物车表格的列标题
这段代码会在购物车表格顶部新增“折扣百分比”列标题:
// 添加购物车表格的折扣百分比列标题 add_filter( 'woocommerce_cart_item_name', 'add_discount_percentage_column_header', 9999, 3 ); function add_discount_percentage_column_header( $product_name, $cart_item, $cart_item_key ) { // 确保只在表格头部添加一次标题 static $added_header = false; if ( ! $added_header && is_cart() ) { $added_header = true; // 将列标题插入到产品名称列之前 $product_name = '<th class="discount-percent">' . __('折扣百分比', 'woocommerce') . '</th>' . $product_name; } return $product_name; }
2. 添加每行的折扣百分比内容
这段代码会为每个促销商品计算并显示折扣百分比,无促销的商品则显示空单元格:
// 在购物车表格行中添加折扣百分比内容 add_filter( 'woocommerce_cart_item_price', 'add_discount_percentage_to_cart_row', 9999, 3 ); function add_discount_percentage_to_cart_row( $price, $cart_item, $cart_item_key ) { $product = $cart_item['data']; // 仅当商品处于促销状态时计算折扣 if ( $product->is_on_sale() ) { $regular_price = (float) $product->get_regular_price(); $sale_price = (float) $product->get_sale_price(); if ( $regular_price > 0 ) { $percentage = round( ( $regular_price - $sale_price ) / $regular_price * 100 ) . '%'; $discount_html = '<td class="discount-percent">' . __('-', 'woocommerce') . $percentage . '</td>'; // 将折扣内容插入到价格单元格前 return $discount_html . $price; } } // 无促销的商品返回空单元格 return '<td class="discount-percent"></td>' . $price; }
3. 可选:调整列的样式
为了让列布局更合理,可将以下CSS代码添加到主题自定义CSS区域:
.woocommerce-cart table.cart th.discount-percent, .woocommerce-cart table.cart td.discount-percent { width: 120px; text-align: center; }
使用说明
将上述PHP代码添加到WordPress主题的functions.php文件中,或使用代码片段插件(如Code Snippets)添加,避免主题更新导致代码丢失。原有产品页的折扣代码无需修改,可与新代码兼容使用。
内容的提问来源于stack exchange,提问作者Agustina Gonzalez
相关产品推荐
相关产品推荐

