Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // WooCommerce - Shortcode to count the number of items purchased by the current user
- add_shortcode( 'itemscount', 'items_count' );
- function items_count() {
- function get_purchased_products() {
- $products = array();
- // get all the customer's 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' => 'on-hold' // Only orders with status "completed"
- ) );
- // go through each of the current customer's orders
- foreach ( $customer_orders as $customer_order ) {
- $order = wc_get_order( $customer_order );
- $items = $order->get_items();
- // go through each order itemr
- foreach ( $items as $item ) {
- $id = $item['product_id'];
- // if product not in the array, add it
- if ( ! array_key_exists( $item['product_id'], $products ) ) {
- $products[ $id ] = array(
- 'name' => $item['name'],
- 'count' => 0,
- );
- }
- // increment product count from cart quantity
- $products[ $id ]['count'] += $item->get_quantity();
- }
- }
- return $products;
- } // end function
- foreach ( get_purchased_products() as $id => $product ) {
- print "<p>$id <b>$product[name]</b> bought $product[count] times</p>";
- }
- } // end function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement