WooCommerce: Get Order info for all users.

WOO version 3+
Type shortcode

Live output from shortcode:

User IDProductQuantitybilling address 1
1test11Street 1
2test 216demo street 1
2test11demo street 1


The code:


add_shortcode('user_order_info_table', 'sc_user_order_info_table_callback');
function sc_user_order_info_table_callback() {

  $result_array = array();
  $users = get_users();

  if($users) {

    foreach ($users as $user) {
      $products_ordered = array();

      $order_args = array(
        'posts_per_page' => -1,
        'meta_key'    => '_customer_user',
        'meta_value'  => $user->ID,
        'post_type'   => 'shop_order',
        'post_status' => 'wc-completed', // only get completed orders
      );
      $orders = get_posts($order_args);

      if($orders) {
        foreach ($orders as $order) {
          $wc_order = wc_get_order( $order->ID );

          foreach ($wc_order->get_items() as $product) {
            $wc_product = wc_get_product($product->get_product_id());

            if($wc_product) { // make sure the product still exists
              if( ! isset( $products_ordered[$product->get_product_id()] ) ) {
                $products_ordered[$product->get_product_id()] = array(
                  'name' => $product->get_name(),
                  'qty' => $product->get_quantity(),
                );
              } else {
                $products_ordered[$product->get_product_id()]['qty'] = $products_ordered[$product->get_product_id()]['qty'] + $product->get_quantity(); // add 1 to quantity
              }

              // get sku example
              //$wc_product->get_sku();
            }
          }
        }
      }

      $customer = new WC_Customer( $user->ID );
			$billing_data = $customer->get_billing('view');
      $user_billing_address1 = $billing_data['address_1'];

      // we have collected all data, save it to array
      $result_array[$user->ID] = array(
        'products_ordered' => $products_ordered,
        'address1' => $user_billing_address1,
      );

    }
  } else {

  }

  // shortcode html output begins hebrev
  $return_html = '';

  foreach ($result_array as $user_id => $data) {
    if( isset($data['products_ordered']) && $data['products_ordered'] ) {
      foreach ($data['products_ordered'] as $product_id => $product_data) {
        $return_html .= '';
        $return_html .= '';
        $return_html .= '';
        $return_html .= '';
        $return_html .= '';
        $return_html .= '';
      }
    }
  }

  $return_html .= '
User IDProductQuantitybilling address 1
'.$user_id.''.$product_data['name'].''.$product_data['qty'].''.$data['address1'].'
'; return $return_html; }