Send a custom email when a specific order item meta is empty in WooCommerce

Viewed 268

I use this code for get meta in some product.

$meta_data = $item->get_formatted_meta_data($hideprefix = '_', $include_all = false );
foreach ($meta_data as $dato){
$datoo = (array) $dato;
$mess .= $datoo['display_key'].': ' .$datoo['value']. '<br>' ;

}

one of these key is "Nome File".

Now i need to send a mail when this meta is empty in all the products.

I need to modify this code but i don't know how...

    // On order completed status
add_action('woocommerce_order_status_processing', 'send_a_custom_email', 20, 1 );
//add_action('woocommerce_order_status_on-hold', 'send_a_custom_email', 20, 1 );
function send_a_custom_email( $order_id ) {
$order = wc_get_order( $order_id ); // The WC_Order object

foreach ( $order->get_items() as $item_id => $item ) {
    $product = $item->get_product(); // The WC_Product object

    // Get the parent product ID for product variations for product categories
    $the_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();

    if (  has_term( array(115, 117, 555, 556, 789, 786, 554), 'product_cat', $the_id ) ) {
    

can someone help me?

1 Answers

here is the the way to a custom email when specific order item meta data is missing (or empty):

add_action('woocommerce_order_status_processing', 'send_a_custom_email', 20, 2 );
// add_action('woocommerce_order_status_on-hold', 'send_a_custom_email', 20, 2 );
function send_a_custom_email( $order_id, $order ) {
    $product_ids = array(); // Initializing
    
    foreach ( $order->get_items() as $item ) {
        $meta_data  = $item->get_meta('Nome File'); // Get order item meta data
        
        if( empty($meta_data) ) {
            $product_ids[] = $item->get_variation_id() > 0 ? $item->get_variation_id() : $item->get_product_id();
        }
    }
    if ( ! empty($product_ids) ) {
        $recipient = 'name@email.com'; // Set email recipient
        $subject   = sprintf( __('Order #%d: Has missing item meta data'), $order_id );
        $content   = sprintf( __('On Order #%d, purchased products %s have missing meta data'), $order_id, implode(', ', $product_ids) );
        wp_mail( $recipient, $subject, $content ); // Send email
    }
}

Code goes in functions.php file of the active child theme (or active theme). It should work.

Related