问题
In WooCommerce I am using WooCommerce Print Invoices & Packing lists plugin…
How can I display the total savings of any order in the invoices generated by this plugin ?
1 year ago I have been using this code based on [this answer] and that was working before I updated WooCommerce :
<?php
$discount_total = 0;
$_order = wc_get_order( $order_id );
foreach ($_order->get_items() as $order_item) {
if ($order_item['variation_id'] > 0) {
$line_item = wc_get_product( $order_item['variation_id'] );
} else {
$line_item = wc_get_product( $order_item['product_id'] );
}
$sale_price = $line_item->sale_price;
$regular_price = $line_item->regular_price;
if ( !empty($sale_price) ) {
$discount = ($regular_price - $sale_price) * $order_item['item_meta']['_qty'][0];
$discount_total += $discount;
}
}
$discount_saving = round ( $discount_total + $_order->get_total_discount() );
if ( $discount_total > 0 ) {
<tr>
<td class="order_saving" colspan="5"><strong><?php _e( 'Total Savings: ', 'woocommerce' ); ?></strong></td>
<td class="value" colspan="2" ><span class="woocommerce-Price-saving saving"><?php echo $discount_saving ; ?></span></td>
</tr>
<?php } ?>
So now it doesn't works anymore. I have tried to make changes without success.
So what is the right solution?
回答1:
Here is the updated code that will work for WooCommerce version 3+:
<?php
///////////// HERE BEGINS CUSTOMIZATION /////////////
$discount_total = 0;
$_order = wc_get_order( $order_id );
foreach ($_order->get_items() as $line_item) {
// The WC_product object
$_product = $line_item->get_product();
// The product prices
$sale_price = $_product->get_sale_price();
$regular_price = $_product->get_regular_price();
if ( !empty($sale_price) ) {
$discount = ($regular_price - $sale_price) * $line_item->get_quantity();
$discount_total += $discount;
}
}
$discount_saving = round ( $discount_total + $_order->get_total_discount() );
if ( $discount_total > 0 ) {
?>
<tr>
<td class="order_saving" colspan="5"><strong><?php _e( 'Total Savings: ', 'woocommerce' ); ?></strong></td>
<td class="value" colspan="2" ><span class="woocommerce-Price-saving saving"><?php echo $discount_saving ; ?></span></td>
</tr>
<?php
}
///////////// END OF CUSTOMIZATION /////////////
?>
This should works for you now
Related threads:
- How to get WooCommerce order details
- Get Order items and WC_Order_Item_Product in Woocommerce 3
来源:https://stackoverflow.com/questions/47639231/display-custom-total-saving-in-generated-invoice-in-woocommerce-3