3

I'm attempting to spit out the lifetime cost of a customers total (completed) orders. The value I'm getting back is equal to the amount if they were not discounted, however I've discounted all the orders to $0, thus it's quite misleading for me to use the data if they haven't paid any money at all. How can I get the value they actually paid, after refunds and discounts applied to that order?

function get_customer_total_order() {
    $customer_orders = get_posts( array(
        'numberposts' => - 1,
        'meta_key'    => '_customer_user',
        'meta_value'  => get_current_user_id(),
        'post_type'   => array( 'shop_order' ),
        'post_status' => array( 'wc-completed' )
    ) );

    $total = 0;
    foreach ( $customer_orders as $customer_order ) {
        $order = wc_get_order( $customer_order );
        $total += $order->get_total();
    }

    return $total;
}
Lukerb
  • 77
  • 2
  • 10
  • 1
    Use $order->get_discount_total(); & $order->get_refunds(); see: https://stackoverflow.com/a/52491796/11987538 – 7uc1f3r Apr 01 '20 at 09:02
  • Cheers managed to get it working using these and similar functions. – Lukerb Apr 02 '20 at 10:18
  • Nice! Can you put the solution to your question below? Afterwards you can mark it as the solution. Regards – 7uc1f3r Apr 02 '20 at 10:23

1 Answers1

1

This was my final function:

// Get customer order total
function has_refunds( $order ) {
    return sizeof( $order->get_refunds() ) > 0 ? true : false;
}
function get_customer_total_order() {
    $customer_orders = get_posts( array(
        'numberposts' => -1,
        'meta_key'    => '_customer_user',
        'meta_value'  => get_current_user_id(),
        'post_type'   => array( 'shop_order' ),
        'post_status' => array( 'wc-completed' )
    ) );

    $total = 0;
    foreach ( $customer_orders as $customer_order ) {
        $order = wc_get_order( $customer_order );

        if( has_refunds( $order ) ) {
        } 
        else
        {
            $price = $order->get_total();

            $discount = $order->get_total_discount();

            $final = $price - $discount;

            $total += $final;
        }

    }

    return $total;
}
Lukerb
  • 77
  • 2
  • 10