I'm trying to display used coupons on WooCommerce order emails + add specific messages based on the used coupons.
Displaying coupons is working based on
Add Applied Coupon Code in Admin New Order Email Template - WooCommerce
I'm trying to expand on it by checking if the string $coupon_codes
contains specific words/specific coupons, in this case "grouppurchase", and then displaying a message.
It needs to be for $coupon_codes
as it can (and will be) used with multiple coupons
I managed to make it work with following code
How do I check if a string contains a specific word?
The problem is (strpos) it displays the message whenever ANY coupon is used, doesn't matter that is written in the coupon, and I can't figure out why
I'm following the strpos logic behind this answer
// Display used Coupons on Emails and Add GroupPurchase Warning
add_action( 'woocommerce_email_after_order_table', 'display_applied_coupons', 10, 4 );
function display_applied_coupons( $order, $sent_to_admin, $plain_text, $email ) {
// Only for admins and when there at least 1 coupon in the order
if ( ! $sent_to_admin && count($order->get_items('coupon') ) == 0 ) return;
foreach( $order->get_items('coupon') as $coupon ){
$coupon_codes[] = $coupon->get_code();
}
// For one coupon
if( count($coupon_codes) == 1 ){
$coupon_code = reset($coupon_codes);
echo '<p>'.__( 'Used Coupon: ').$coupon_code.'<p>';
}
// For multiple coupons
else {
$coupon_codes = implode( ', ', $coupon_codes);
echo '<p>'.__( 'Used Coupons: ').$coupon_codes.'<p>';
}
if (strpos($coupon_codes, 'groupurchase') !== false) {
echo '<p>' . 'With this coupon you are participating in a group purchase' . '<p>' ;
}
}
Give it a try this way
// The email function hooked that display the text
function display_applied_coupons( $order, $sent_to_admin, $plain_text, $email ) {
// Only for admins and when there at least 1 coupon in the order
if ( ! $sent_to_admin && count($order->get_items('coupon') ) == 0 ) return;
foreach( $order->get_items('coupon') as $coupon ){
$coupon_codes[] = $coupon->get_code();
}
// For one coupon
if( count( $coupon_codes ) == 1 ){
$coupon_code = reset( $coupon_codes );
// Set variable output
$output = '<p>' . __( 'Coupon Used: ', 'woocommerce' ) . $coupon_code . '</p>';
// Extra
if ( strpos( $coupon_code, 'groupurchase') !== false ) {
// Append to
$output .= '<p>' . __('With this coupon you are participating in a group purchase', 'woocommerce') . '</p>';
}
// Echo output
echo $output;
} else { // For multiple coupons
// Loop
foreach ( $coupon_codes as $coupon_code ) {
// Set variable output
$output = '<p>' . __( 'Coupon Used: ', 'woocommerce' ) . $coupon_code . '</p>';
// Extra
if ( strpos( $coupon_code, 'groupurchase') !== false ) {
// Append to
$output .= '<p>' . __('With this coupon you are participating in a group purchase', 'woocommerce') . '</p>';
}
// Echo output
echo $output;
}
}
}
add_action( 'woocommerce_email_order_details', 'display_applied_coupons', 10, 4 );