• Resolved sonofara

    (@sonofara)


    found this code but it wont show quantities…

    function items_count() {
    
    	function get_purchased_products() {
    	    $products = array();
    
    	    // Get all customer orders
    	    $customer_orders = get_posts( array(
    	        'numberposts' => - 1,
    	        'meta_key'    => '_customer_user',
    	        'meta_value'  => get_current_user_id(),
    	        'post_type'   => 'shop_order', // WC orders post type
    	        'post_status' => 'wc-completed' // Only orders with status "completed"
    	    ) );
    
    	    // Going through each current customer orders
    	    foreach ( $customer_orders as $customer_order ) {
    	        $order    = wc_get_order( $customer_order );
    	        $items    = $order->get_items();
    
    	        // Going through each current customer products bought in the order
    	        foreach ( $items as $item ) {
    	            $id = $item['product_id'];
    
    	            // If product not in array, add it
    	            if ( ! array_key_exists( $item['product_id'], $products ) ) {
    	                $products[ $id ] = array(
    	                    'name' => $item['name'],
    	                    'count' => 0,
    	                );
    	            }
    
    	            // Increment Product <code>count</code> from cart quantity
    	            $products[ $id ]['count'] += $item['item_meta']['_qty'][0];
    	        }
    	    }
    
    	    return $products;
    	}
    	foreach ( get_purchased_products() as $id => $product ) {
    	    echo "<p>$id <b>$product[name]</b> bought $product[count] times</p>";
    	}
    
    }
    add_shortcode( 'itemscount', 'items_count' );

    I get following output:
    Pepsi bought 0 times
    Coke bought 0 times
    Apples bought 0 times

    • This topic was modified 6 years, 9 months ago by sonofara.
Viewing 4 replies - 1 through 4 (of 4 total)
  • Using _qty is accessing values directly which is a deprecated method of accessing data, so you’ll need to use the newer getter function:
    $products[ $id ]['count'] += $item->get_quantity();

    Thread Starter sonofara

    (@sonofara)

    Superb! Thanks @lorro

    Thread Starter sonofara

    (@sonofara)

    is there a way to count all order for specific product category?

    Caleb Burks

    (@icaleb)

    Automattic Happiness Engineer

    All the orders that contain a product from a specific category? WooCommerce > Reports > Orders > Sales by category will show total sales amount.

    To get a list of order IDs is possible, but going to take some custom queries / reports.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Count Completed Orders For specific Product’ is closed to new replies.