仅当客户未使用优惠券时,才将优惠券添加到处理订单电子邮件中

Add coupon to the processing order email only if the customer have not used one

我发现了这个将优惠券添加到订单邮件中的片段。

我想让它只在客户没有使用任何优惠券的情况下出现在处理订单邮件中。

add_action( 'woocommerce_email_before_order_table', 'add_content', 20 );

function add_content() {
echo '<h2 id="h2thanks">Get 20% off</h2><p id="pthanks">Thank you for making this purchase! Come back and use the code "<strong>Back4More</strong>" to receive a 20% discount on your next purchase! Click here to continue shopping.</p>';
}

谢谢。

@update 2: New orders are most of the time in 'on-hold' status, but not in 'Processing'.
In this case, use this instead:

add_action( 'woocommerce_email_before_order_table', 'processing_order_mail_message', 20 );
function processing_order_mail_message( $order ) {
    if ( empty( $order->get_used_coupons() ) && $order->post_status == 'wc-on-hold' )
        echo '<h2 id="h2thanks">Get 20% off</h2><p id="pthanks">Thank you for making this purchase! Come back and use the code "<strong>Back4More</strong>" to receive a 20% discount on your next purchase! Click here to continue shopping.</p>';
}

Or to handle both 'on-hold' AND 'processing' statuses use this:

add_action( 'woocommerce_email_before_order_table', 'processing_order_mail_message', 20 );
function processing_order_mail_message( $order ) {
    if ( empty( $order->get_used_coupons() ) && ( $order->post_status == 'wc-on-hold' || $order->post_status == 'wc-processing' ) )
        echo '<h2 id="h2thanks">Get 20% off</h2><p id="pthanks">Thank you for making this purchase! Come back and use the code "<strong>Back4More</strong>" to receive a 20% discount on your next purchase! Click here to continue shopping.</p>';
}

This code goes on function.php file of your active child theme or theme

此代码已经过测试且功能齐全


TESTING:
To display the status of the emailed order you can add in the function this line:

echo '<p>The status of this order is: ' . $order->post_status . '</p>';

To display the coupons used (if they are some) add this:

echo '<p>Coupons used in this order are: '; print_r( $order->get_used_coupons() ); echo '</p>'

(this is just for testing purpose).


Original answer:

是的,可以很容易地 添加带有 2 个条件的 if 语句

第一个检测订单中是否使用过优惠券:

empty( $order->get_used_coupons() )

而第二个将检测订单是否处于 "processing" 状态:

$order->post_status == 'wc-processing'

如果满足这些条件,您的消息将使用**'woocommerce_email_before_order_table'** 挂钩显示:

这是您的自定义代码片段:

add_action( 'woocommerce_email_before_order_table', 'processing_order_mail_message', 20 );
function processing_order_mail_message( $order ) {
    if ( empty( $order->get_used_coupons() ) && $order->post_status == 'wc-processing' )
        echo '<h2 id="h2thanks">Get 20% off</h2><p id="pthanks">Thank you for making this purchase! Come back and use the code "<strong>Back4More</strong>" to receive a 20% discount on your next purchase! Click here to continue shopping.</p>';
}

此代码位于您的活动子主题或主题的 function.php 文件中

此代码已经过测试且功能齐全