Get order subtotal value in WooCommerce

痞子三分冷 提交于 2021-02-05 08:28:30

问题


I use the module for calculating delivery by local carrier, but the module don't calculate shipping costs to the total.
In the wp-content/plugins/woocommerce/templates/order/order-details.php I added the following code to take the amount of shipping and subtotal:

     <?php $a = array(
         get_post_meta($order_id, 'Order_subtotal', true),
         get_post_meta($order_id, 'Econt_Customer_Shipping_Cost', true));
     ?>
     <tr class="total-cost">
         <th><?php _e( 'Total:', 'woocommerce'); ?></th>
         <td><?php echo array_sum($a); ?> <?php echo get_woocommerce_currency_symbol(); ?></td>
     </tr>

As a result, I get only the value of "Econt_Customer_Shipping_Cost", but not from "Order_subtotal" to get the total.

Please, can someone tell me what to use to get a working subtotal?


回答1:


First 'Order_subtotal' does not exist in wp_postmeta table for 'shop_order' post-type.

Last very important thing: Don't overrinde templates directly in woocommerce plugin, to avoid loosing your changes when plugin is updated. You can better override this files by copying this 'templates' folder to your active child theme or theme and rename it woocommerce.
See this reference: Overriding WooCommerce Templates via a Theme…


Changing your code (the answer)

As you have already at the beginning of this template $order = wc_get_order( $order_id );, you can use the class WC_Abstract_Order native functions get_subtotal( ) or get_total( ) directly from $order, without using get_post_meta() Wordpress function.

I have changed some things in your code:

<?php 
    $display_sum = $order->get_subtotal( ); // or $order->get_total( );
    $display_sum += get_post_meta( $order->id, 'Econt_Customer_Shipping_Cost', true );
    $display_sum .= ' '. get_woocommerce_currency_symbol( );
?>
<tr class="total-cost">
    <th><?php _e( "Total:", "woocommerce" ); ?></th>
    <td><?php echo $display_sum; ?></td>
</tr>

This should work as you want it, but this will not update the order total, it just display it.

References:

  • Class - WC_Abstract_Order
  • WooCommerce get order total



回答2:


Try this code $order_total = get_post_meta ($order_id , '_order_total', true);




回答3:


Try this $order->get_subtotal_to_display();



来源:https://stackoverflow.com/questions/38105310/get-order-subtotal-value-in-woocommerce

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