I am trying to get each tag of the products ordered added to the Admin New Order Email. I also need the name of the product added in, which I’m able to do, but can’t seem to get the tags. Here’s the code I have:

add_filter('woocommerce_email_subject_new_order', 'change_admin_email_subject', 10, 2);
function change_admin_email_subject( $subject, $order ) {
    $products_names = array();
    $product_id = array();
    $product_tag = array();

    foreach ( $order->get_items() as $item_id => $item ) {
        $products_names[] = $item->get_name();
        $product_id[] = $order->get_item_meta($item_id, '_product_id', true); // product ID
        $product_tag[] = get_the_terms($product_id, 'product_tag');
    }

    return sprintf( '[%s] New Order (#%s): Season: %s, Item: %s from %s %s',
        wp_specialchars_decode(get_option('blogname'), ENT_QUOTES),
        $order->get_id(),
        implode(', ', $product_tag),
        implode(', ', $products_names),
        $order->get_billing_first_name(),
        $order->get_billing_last_name()
    );
}

But this just produces a blank array.
Any help would be awesome.

1 Answer
1

You are getting a blank array because you are storing arrays of WP_Term product tags Objects in an array, and then using implode() on a multidimensional array of WP_Term objects which gives a first error and finally a second error on the sprintf() function.

Is better to use wp_get_post_terms() that allows to get term names instead of WP_Term objects.

You should also need to remove duplicated product names or/and product tags term names.

Try the following instead:

add_filter('woocommerce_email_subject_new_order', 'change_admin_email_subject', 10, 2);
function change_admin_email_subject( $subject, $order ) {
    $products_names = $products_tags = [];

    foreach ( $order->get_items() as $item ) {
        // Get the product tags term names in an array
        $term_names = wp_get_post_terms($item->get_product_id(), 'product_tag', ['fields' => 'names']);

        $products_tags    = array_merge($products_tags, $term_names);
        $products_names[] = $item->get_name();
    }

    return sprintf( '[%s] New Order (#%s): Season: %s, Item: %s from %s %s',
        wp_specialchars_decode(get_option('blogname'), ENT_QUOTES),
        $order->get_order_number(),
        implode(', ', array_unique($products_tags)), 
        implode(', ', array_unique($products_names)),
        $order->get_billing_first_name(),
        $order->get_billing_last_name()
    );
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Leave a Reply

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