Get List of Coupons used by one Customer in all WooCommerce orders
The beauty of code snippets is their ability to save you time when developing a site.
If you are a WooCommerce developer you may find this snippet usefull for Coupons listing.
Have fun!
<?php /* * ============================================================== * Display all coupons used by one customer * ============================================================== */ global $current_user,$woocommerce; $current_user = wp_get_current_user(); $customer_id = $current_user->ID; $args = array( 'numberposts' => -1, 'meta_key' => '_customer_user', 'meta_value' => $customer_id, 'post_type' => 'shop_order', 'post_status' => 'publish' ); $customer_orders = get_posts($args); if ($customer_orders) : foreach ($customer_orders as $customer_order) : $order = new WC_Order(); $order->populate( $customer_order ); // Get the coupon array $couponR = $order->order_custom_fields['coupons']; foreach ($couponR as $singleCoupon) { echo $singleCoupon.'<br />'; } endforeach; else : //no Coupon then... endif; ?>
Hello Milan, I could surely use this info. Could you please give me an example of how to implement this. I run some WordPress sites and I’m a bit new on running PHP code. Do I create this in it’s own .php file and copy it to the theme directory??
Thanks!
Hi Tony,
Thanks for the comment and I’m glad that you find our snippet useful.
In order to use it properly you should have some basic PHP knowledge and learn how the use of functions.php file.
Depending on what you want to accomplish this snippet itself could be used both in theme template files and functions.php. Below is a fast example on how you could create a function from the snippet in functions.php file:
function my_superawesome_function() {
$current_user = wp_get_current_user();
$customer_id = $current_user->ID;
$args = array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => $customer_id,
'post_type' => 'shop_order',
'post_status' => 'publish'
);
$customer_orders = get_posts($args);
if ($customer_orders) :
foreach ($customer_orders as $customer_order) :
$order = new WC_Order();
$order->populate( $customer_order );
// Get the coupon array
$couponR = $order->order_custom_fields['coupons'];
foreach ($couponR as $singleCoupon) {
echo $singleCoupon.'
';
}
endforeach;
else :
//no Coupon then...
endif;
}
add_action('woocommerce_before_order_notes', 'my_superawesome_function');
I hope it helps and happy coding