mrkeck Sharing the Love

4Feb/150

WooCommerce get Quantity of Items Purchased by a User

Get any Attribute for a User Grouped by Item or One Specific Item for use in WordPress Plugin

//UserId, Attribute, [Specific Item]
//Attribute will prepend '_' if left off to make it more readable
$qtyForAllItemsUserPurchased = wooAttr(get_current_user_id(), 'qty');
$qtyForOneItemUserPurchased = wooAttr(get_current_user_id(), 'qty', "Example Item 123");
 
function wooAttr( $user, $attr, $item = NULL ){
	global $wpdb;
	if( substr($attr, 0, 1) != '_' ){
		$attr = '_' . $attr;
	}
	if(is_null($item)){
		$sql = $wpdb->prepare("SELECT oi.order_item_name item, SUM(oim.meta_value) val FROM wp_posts p JOIN wp_woocommerce_order_items oi ON p.ID = oi.order_id JOIN wp_woocommerce_order_itemmeta oim ON oi.order_item_id = oim.order_item_id WHERE oim.meta_key = %s AND p.post_author = %d GROUP BY item", $attr, $user);
	}else{
		$sql = $wpdb->prepare("SELECT oi.order_item_name item, SUM(oim.meta_value) val FROM wp_posts p JOIN wp_woocommerce_order_items oi ON p.ID = oi.order_id JOIN wp_woocommerce_order_itemmeta oim ON oi.order_item_id = oim.order_item_id WHERE oim.meta_key = %s AND p.post_author = %d AND oi.order_item_name = %s GROUP BY item", $attr, $user, $item);
	}
	return $wpdb->get_results( $sql , ARRAY_A );
}
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.