I'm trying to echo some text in the order completed email generated by WooCommerce according to a set of conditions based on the product category in the order table.
I have 4 product categories (cat-one, cat-two, cat-three, cat-four).
One category has variable products (just in case it matters although I was testing on orders without it)
The conditions I'd like to have are:
- Only for customer order completed email
- IF the order has only products in cat-one THEN use "SOME TEXT"
- IF the order has products in cat-one AND products from any other categories THEN use "SOME OTHER TEXT"
- IF the order has products from ALL categories except cat-one THEN use "ANOTHER TEXT"
What I have tried so far:
function add_instructions_to_email( $order, $sent_to_admin, $plain_text, $email ) {
$cat_one = false;
$cat_two = false;
$cat_three = false;
$cat_four = false;
$items = $order->get_items();
foreach ( $items as $item ) {
$product_id = $item->get_product_id();
//CHECK WHICH CATEGORIES ARE IN THE ORDER
if ( has_term( 'cat_one', 'product_cat', $product_id ) ) {
$cat_one=true;
}
if ( has_term( 'cat_two', 'product_cat', $product_id ) ) {
$cat_two=true;
}
if ( has_term( 'cat_three', 'product_cat', $product_id ) ) {
$cat_three=true;
}
if ( has_term( 'cat_four', 'product_cat', $product_id ) ) {
$cat_four=true;
}
if ( $email->id == 'customer_completed_order') {
// 1. ONLY CAT-ONE
if ( $cat_one) {
echo "SOME TEXT";
}
// 2. CAT-ONE and any other Category
elseif ( $cat_one && $cat_two || $cat_three || $cat_four) {
if($order->has_shipping_method('local_pickup')) {
echo "SOME TEXT";
} else {
echo "SOME OTHER TEXT";
}
}
// 3. THERE IS NO CAT-ONE IN THE ORDER
elseif ( !$cat_one && $cat_two || $cat_three || $cat_four ) {
if ($order->has_shipping_method('local_pickup')) {
echo "SOME TEXT";
} else {
echo "SOME OTHER TEXT";
}
}
}
add_action( 'woocommerce_email_before_order_table', 'add_instructions_to_email', 20, 4 );
It's not working as expected. I also tried using elseif
statements in the foreach
and conditionals directly in the has_term
statement. No success.
Any help appreciated.