Count Completed Orders For specific Product
-
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
Viewing 4 replies - 1 through 4 (of 4 total)
Viewing 4 replies - 1 through 4 (of 4 total)
- The topic ‘Count Completed Orders For specific Product’ is closed to new replies.