WooCommerce: Calculate Sales by Coupon Code

A #BloomerArmada fan had a nice challenge with a client – how to display the total amount of sales generated by a given coupon code?

And, as fans are VIPs to me, I was able to create this snippet and make this blog skip the queue of contents I have in my long list – so there you go!

WooCommerce: sales by coupon code

PHP Snippet: Show Total Sales by Coupon Code

 

/**
* @snippet Get Total Sales by COUPON
* @how-to Get CustomizeWoo.com FREE
* @sourcecode https://businessbloomer.com/?p=72576
* @author Rodolfo Melogli
* @testedwith WooCommerce 3.0.7
*/

// -------------------------
// 1. Create function that calculates sales based on coupon code

function bbloomer_get_sales_by_coupon($coupon_id) {

    $args = [
        'post_type' => 'shop_order',
        'posts_per_page' => '-1',
        'post_status' => ['wc-processing', 'wc-completed', 'wc-on-hold']
    ];
    $my_query = new WP_Query($args);
    $orders = $my_query->posts;

    $total = 0;

    foreach ($orders as $key => $value) {
   
	$order_id = $value->ID;
	$order = wc_get_order($order_id);
	$items = $order->get_items('coupon'); 

	foreach ( $items as $item ) {

	if( $item['code'] == $coupon_id ) {
                $total += $order->get_total();
        }

	}
	
    }
    return 'Total sales for coupon "' . $coupon_id . '": ' . wc_price($total);
}

// -------------------------
// 2. Add new tab to WooCommerce "Reports", and print the coupon total sales

add_filter( 'woocommerce_admin_reports', 'bbloomer_add_report_tab' );

function bbloomer_add_report_tab( $reports ) {

$reports['coupons'] = array(
				'title'  => __( 'Coupons', 'woocommerce' ),
				'reports' => array(
					"sales_by_code" => array(
						'title'       => __( 'Sales by code', 'woocommerce' ),
						'description' => bbloomer_get_sales_by_coupon('barmada'), //change coupon code here
						'hide_title'  => false,
						'callback'    => '',
					),
				),
			);

return $reports;
}

Where to add this snippet?

You can place PHP snippets at the bottom of your child theme functions.php file (before "?>" if you have it). CSS, on the other hand, goes in your child theme style.css file. Make sure you know what you are doing when editing such files - if you need more guidance, please take a look at my free video tutorial "Where to Place WooCommerce Customization?"

Does this snippet (still) work?

Please let me know in the comments if everything worked as expected. I would be happy to revise the snippet if you report otherwise (please provide screenshots). I have tested this code with Storefront theme, the WooCommerce version listed above and a WordPress-friendly hosting on PHP 7+.

If you think this code saved you time & money, please join other Business Bloomer supporters and avail of 365 days of WooCommerce benefits. Thank you in advance :)

Need Help with WooCommerce Customization?

Check out these free video tutorials. You can start learning how to customize WooCommerce without unnecessary plugins. Watch me code and learn by example!

  • how-to-edit-woocommerce-with-php-snippets
  • woocommerce-hooks-add_action-list-visual
  • woocommerce-customize-single-product-page-PHP

Rodolfo Melogli

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as a WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza.

12 thoughts on “WooCommerce: Calculate Sales by Coupon Code

  1. Thanks for the snippets. This saves me a lot of time.

    1. Great!

  2. Hi Rodolfo,
    Thanks for all of the snippets you have provided! We’re running this one on a client site that uses Woocommerce Subscriptions and sells some products that automatically renew on a monthly or weekly basis. Recently, we noticed that renewal payments weren’t processing unless we turned this snippet off. We also couldn’t change our subscriptions’ statuses without receiving timeout errors when this snippet was active. Any ideas about what might be going on? Thanks again for all of your insights into Woocommerce!

    1. Hi Laura – I guess you’ve customized the snippet to return multiple coupon codes and their totals? Maybe there is something wrong in your code that needs troubleshooting in this case, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  3. Actually, it didn’t work for me. Latest version.

    1. Hi Stef! What didn’t work exactly?

  4. How to display 2 coupons?

    1. Hey Nghia, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  5. Hi Rodolfo,

    Thanks for the new snippet. I have tested it but I seem to have an issue. Please see the screenshot: http://imgur.com/a/3RCFf

    I copied your code snipped and only changed the coupon code here:

    ‘description’ => bbloomer_get_sales_by_coupon(‘barmada’), //change coupon code here

    I don’t see any reason for this to happen, have you had this issue?

    1. Hey John, thanks for your comment! I think I made a mistake in the snippet (now corrected). Can you try changing:

      echo wc_price($total);
      

      with:

      return 'Total sales for coupon "' . $coupon_id . '": ' . wc_price($total);
      

      Let me know ๐Ÿ™‚

    2. Thanks Rodolfo,

      Now working perfectly. Is there a way to show the sales for all the coupons codes?

      1. Brilliant ๐Ÿ™‚ Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here on the blog. Thanks a lot for your understanding! ~R

Questions? Feedback? Support? Leave your Comment Now!
_____

If you are writing code, please wrap it between: [php]code_here[/php]. Failure to complying with this (as well as going off topic) will result in comment deletion. You should expect a reply in about a week - this is a popular blog but I need to get paid work done first. Please consider joining #BloomerArmada to ask me 1-to-1 WooCommerce questions. Thank you :)

Your email address will not be published. Required fields are marked *