2

I'm trying to get the price of all products on hold (i.e user has placed order but haven't made a payment) by a user in woocommerce.

I have the following code which detects all products on-hold orders by a user

function get_user_on_hold_product_price() {

    global $product, $woocommerce;

    // GET USER
    $current_user = wp_get_current_user();

    // GET USER ON-HOLD ORDERS
    $customer_orders = get_posts( array(
        'numberposts' => -1,
        'meta_key'    => '_customer_user',
        'meta_value'  => $current_user->ID,
        'post_type'   => 'shop_order',
        'post_status' => 'wc-on-hold',
    ) );

I'm not sure what to do from here to get only the total price of all on-hold orders by the user.

Adding/hooking this function to a shortcode, like this;

add_shortcode('get_on-hold_price', 'get_user_on_hold_product_price')

Thanks

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399

1 Answers1

1

To get the total amount of customer "on-hold" orders using a WC_Order_Query for improved usability and compatibility:

add_shortcode('user_on_hold_total', 'get_user_orders_on_hold_total');
function get_user_orders_on_hold_total() {
    $total_amount = 0; // Initializing

    // Get current user
    if( $user = wp_get_current_user() ){

        // Get 'on-hold' customer ORDERS
        $on_hold_orders = wc_get_orders( array(
            'limit' => -1,
            'customer_id' => $user->ID,
            'status' => 'on-hold',
        ) );

        foreach( $on_hold_orders as $order) {
            $total_amount += $order->get_total();
        }
    }
    return $total_amount;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

To get a formatted total amount replace return $total_amount; by return wc_price($total_amount);

Shortcode usage: [user_on_hold_total]

Related documentation: Woocommerce wc_get_orders() and WC_Order_Query

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399