在购物车表上添加列折扣 woocommerce
P粉807471604
2023-08-31 11:32:05
[PHP讨论组]
<p>你好,我想在购物车表中添加一列,其中包含折扣百分比
你能帮我吗?</p>
<p>我有产品页面的代码</p>
<pre class="brush:php;toolbar:false;">////__________________________________________________________________________________________////
//AGREGA EL PORCENTAJE DE DESCUENTO JUNTO AL PRECIO MAYORISTA
// Only for WooCommerce version 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;
}</pre></p>
向购物车页面添加一列(其值取决于购物车商品)的最简单方法是覆盖
cart.php模板。从 WooCommerce 插件中,复制 woocommerce/cart/cart.php 到
yourTheme/woocommerce/cart/。如果您没有使用子主题,我建议您创建一个子主题并通过它覆盖模板,这样当您的主题更新时,您的模板更改就不会丢失。有关子主题的更多信息。从那里您可以查看
cart.php,找到要插入折扣百分比标题的位置,并插入数据(在本例中为百分比折扣)。 p>要获取表头的标签,很简单。只需在表格的
thead中添加标签的 HTML 即可。在我的示例中,可以在cart.php 第 51-59 行中找到:<thead> <tr> <th class="product-name" colspan="3"><?php esc_html_e( 'Product', 'woocommerce' ); ?></th> <th class="product-price"><?php esc_html_e( 'Price', 'woocommerce' ); ?></th> <th class="product-discount"><?php esc_html_e( 'Discount', 'woocommerce' ); ?></th> // added this line <th class="product-quantity"><?php esc_html_e( 'Quantity', 'woocommerce' ); ?></th> <th class="product-subtotal"><?php esc_html_e( 'Subtotal', 'woocommerce' ); ?></th> </tr> </thead>要获取并显示折扣百分比,您必须浏览模板并找到它的正确位置。在我的示例中,我将其放在价格和数量之间,直接在折扣标题下方。在
cart.php中,这将是第102行。从那里,您只需编写 HTML 和 PHP 代码即可根据购物车商品的正常价格和促销价计算百分比:<td class="product-discount"> <?php if($_product->get_sale_price() != ''){ $reg_price = $_product->get_regular_price(); $sale_price = $_product->get_sale_price(); $percentage = ((($sale_price / $reg_price) - 1) * -1) * 100 . "%"; echo $percentage; } ?> </td>您现在可以看到,在购物车页面上,它显示了基于购物车商品的折扣百分比. 在我的示例中,顶部产品正在促销,底部产品不促销。