Emilio Venegas
Emilio Venegas

Reputation: 556

WooCommerce Getting the product quantity in a order based on wc_customer_bought_product function

I'm using the wc_customer_bought_product() function to check if the current user has bought a certain product.

However, now I need to check how many of that product did the customer buy.

So, for example, if I have bought in an order a product with a quantity of 7, I'd need a way to get the order and the quantity in that order for this product.

How can I achieve this?

If anyone have some answer, it would be much appreciated.

Upvotes: 1

Views: 5295

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253784

Here you have All material to build your own function. Below this is an example with a function that will get the product quantity in an order based on a product ID for a current customer, using the function wc_customer_bought_product():

function checking_product_bought( $_product_id ){

    global $woocommerce, $posts;

    // Get the current customer info (as an object)
    $customer      = wp_get_current_user();
    $customer_id   = $customer->ID; // customer ID
    $customer_email = $customer->email; // customer email

    // Get all orders for this customer_id
    $customer_orders = get_posts( array(
        'numberposts' => -1,
        'meta_key'    => '_customer_user',
        'meta_value'  => $customer_id,
        'post_type'   => wc_get_order_types(),
        'post_status' => array_keys( wc_get_order_statuses() ),
    ) );

    if ( $customer_orders ){

        foreach ( $customer_orders as $customer_order ) {
            $order        = wc_get_order();
            $order_id     = $order->id; // get the order ID )or may be "order->ID")
            // getting all products items for each order
            $items = $order->get_items();

            foreach ($items as $item) 
            {
                $product_id = $item['product_id']; // product id
                $product_qty = $item['qty']; // product quantity

                if(wc_customer_bought_product( $customer_email, $customer_id, $_product_id)) 
                {
                    echo '<div>for order number: ' . $order_id . ' ,there is ' . $product_qty . ' for this product.';
                }

            }

        }

    }

}

References:

Upvotes: 5

Related Questions