Advertisement
majeedraza

WooCommerce - Shortcode to count the number of items purchas

Mar 1st, 2018
319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.45 KB | None | 0 0
  1. <?php
  2.  
  3. // WooCommerce - Shortcode to count the number of items purchased by the current user
  4.  
  5. add_shortcode( 'itemscount', 'items_count' );
  6. function items_count() {
  7.  
  8.   function get_purchased_products() {
  9.     $products = array();
  10.     // get all the customer's orders
  11.     $customer_orders = get_posts( array(
  12.       'numberposts' => - 1,
  13.       'meta_key'    => '_customer_user',
  14.       'meta_value'  => get_current_user_id(),
  15.       'post_type'   => 'shop_order', // WC orders post type
  16.       'post_status' => 'on-hold' // Only orders with status "completed"
  17.     ) );
  18.  
  19.     // go through each of the current customer's orders
  20.     foreach ( $customer_orders as $customer_order ) {
  21.       $order    = wc_get_order( $customer_order );
  22.       $items    = $order->get_items();
  23.       // go through each order itemr
  24.       foreach ( $items as $item ) {
  25.         $id = $item['product_id'];
  26.         // if product not in the array, add it
  27.         if ( ! array_key_exists( $item['product_id'], $products ) ) {
  28.           $products[ $id ] = array(
  29.             'name' => $item['name'],
  30.             'count' => 0,
  31.           );
  32.         }
  33.         // increment product count from cart quantity
  34.         $products[ $id ]['count'] += $item->get_quantity();
  35.       }
  36.     }
  37.     return $products;
  38.   } // end function
  39.  
  40.   foreach ( get_purchased_products() as $id => $product ) {
  41.     print "<p>$id <b>$product[name]</b> bought $product[count] times</p>";
  42.   }
  43. } // end function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement