add column discount on cart table woocommerce
P粉807471604
2023-08-31 11:32:05
<p>Hello, I want to add a column to the shopping cart table that contains the discount percentage
Can you help me? </p>
<p>I have the code for the product page</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>
The easiest way to add a column to the cart page (whose value depends on the cart items) is to override the
cart.php
template.From the WooCommerce plugin, copy woocommerce/cart/cart.php to
yourTheme/woocommerce/cart/
. If you are not using a child theme, I recommend creating one and overriding the template through it so that when your theme is updated, your template changes are not lost. More information on subtopic.From there you can look at
cart.php
, find where you want to insert the discount percentage header, and insert the data (in this case, the percentage discount). p>It is very simple to get the label of the table header. Just add the HTML of the tag in the
thead
of the table. In my example this can be found incart.php lines 51-59
:To get and display the discount percentage, you must browse the template and find its correct location. In my example, I placed it between price and quantity, directly below the discount title. In
cart.php
, this would beline 102
. From there, you just write HTML and PHP code to calculate the percentage based on the regular and sale prices of your cart items:You can now see that on the cart page it shows the discount percentage based on the cart items. In my example the top product is on sale and the bottom product is not.