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;
}

Share:

Leave a Reply