Display the Remaining Stock Quantity for each order item only in WooCommerce new order email notification

Loading

There is an alternative code solution that you should use:

// Setting the email ID as a global variable
add_action('woocommerce_email_before_order_table', 'set_the_email_id_as_a_global_variable', 1, 4);
function set_the_email_id_as_a_global_variable($order, $sent_to_admin, $plain_text, $email){
    $GLOBALS['email_id_str'] = $email->id;
}

// Display product remaining stock quantity on order items
add_action( 'woocommerce_order_item_meta_start', 'display_remaining_stock_quantity', 10, 3 );
function display_remaining_stock_quantity( $item_id, $item, $order ) {
    // Only for order item "line item" type
    if ( !$item->is_type('line_item') ) {
        return;
    }
    $globalsVar = $GLOBALS; // Pass $GLOBALS variable as reference

    // Try to get the email ID from globals reference 
    if( isset($globalsVar['email_id_str']) && $globalsVar['email_id_str'] === 'new_order' ) {
        $product = $item->get_product();

        if ( $stock_qty = $product->get_stock_quantity() ) {
            printf('<div>%s: %d</div>', __('Remaining stock', 'woocommerce'), $stock_qty);
        }
    }
}

Code goes in function.php file of your child theme (or in a plugin). Tested and works. It may work on your side, avoiding the issue you describe.

About Post Author