P粉8934570262023-09-01 00:25:02
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 in cart.php lines 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>
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 be line 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:
<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>
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.