WooCommerce: Get Order info for all users.
I was trying to help you get going.. After a while i had a complete solution :S…
So here it is, a tested single shortcode that outputs your <table>
(WooCommerce 3+ only):
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();
}
// 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="<table><thead><tr><td>User ID</td><td>Product</td><td>Quantity</td><td>billing address 1</td></tr></thead><tbody>";
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 .= '<tr>';
$return_html .= '<td>'.$user_id.'</td>';
$return_html .= '<td>'.$product_data['name'].'</td>';
$return_html .= '<td>'.$product_data['qty'].'</td>';
$return_html .= '<td>'.$data['address1'].'</td>';
$return_html .= '</tr>';
}
}
}
$return_html .= '</tbody></table>';
return $return_html;
}
Place this snippet in your (child) theme functions.php.
Use the shortcode [user_order_info_table]
in posts and pages wherever you want.
See it @ work here in my sandbox.
NOTE: it works, but this is not a ‘final release’ ready for shipping. You probably want to do some more error handling etc.
Regards, Bjorn