Skip to content
Advertisement

WooCommerce – get customer lifetime order cost adjusting for discounts AND refunds

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;
}

Advertisement

Answer

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;
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement