Display Custom Total Saving in generated invoice in WooCommerce 3

自闭症网瘾萝莉.ら 提交于 2020-01-13 20:21:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!