questions

Check if user is VAT exempt on WooCommerce email notifications

Rate this post

On WooCommerce new order email notification sent to the admin I am trying to display “Tax Free Order” additional text when user “is Vat exempt”, using the following:

add_action( 'woocommerce_email_before_order_table', 'add_content_specific_email', 20, 4 );

function add_content_specific_email($order, $sent_to_admin, $plain_text, $email) {
    // Only for admin emails
    if ( ! $sent_to_admin ) {
        return;
    }
    if ( $email->id == 'new_order' &&  !(WC()->customer->get_is_vat_exempt()) && $sent_to_admin ){
        return;
    }
    if ( $email->id == 'new_order' &&  WC()->customer->get_is_vat_exempt() && $sent_to_admin) {
        echo '<h2 class="email-tax-free-title">Tax Free Order</h2></p>';
    }
}

In some cases, I get the following error:

Uncaught Error: Call to a member function get_is_vat_exempt() on null
#0 /home/site/public_html/wp-includes/class-wp-hook.php(287): add_content_specific_email(Object(Automattic\WooCommerce\Admin\Overrides\Order), true, false, Object(WC_Email_New_Order))
#1 /home/site/public_html/wp-includes/class-wp-hook.php(311): WP_Hook->apply_filters(NULL, Array)
#2 /home/site/public_html/wp-includes/plugin.php(478): WP_Hook->do_action(Array)
#3 /home/site/public_html/wp-content/plugins/woocommerce/templates/emails/email-order-details.php(22): do_action('woocommerce_ema...', Object(Automattic\WooCommerce\Admin\Overrides\Order), true, false, Object(WC_Email_New_Order))
#4 /home/site/public_html/wp-content/plugins/woocommerce/includes/wc-core-functions.php(344): include('/home/site/...')
#5 /home/site/public_html/wp-content/plugins/woocommerce/includes/class-wc-emails.php(421): wc_get

How can I solve this error? Is there a mistake in my code?

 

✔️Solution:

There are some mistakes in your code. To avoid this error, you need to check if order meta data is_vat_exempt value is ‘yes’, as follows:

add_action( 'woocommerce_email_before_order_table', 'new_order_email_is_vat_exempt', 20, 4 );
function new_order_email_is_vat_exempt( $order, $sent_to_admin, $plain_text, $email ) {
    // Only for new order admin email notification
    if ( $sent_to_admin && 'new_order' === $email->id ) {
        // Check if user is VAT exempt for the current order
        if( 'yes' === $order->get_meta( 'is_vat_exempt' ) ) {
            echo '<h2 class="email-tax-free-title">Tax Free Order</h2></p>';
        }
    }
}

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

Leave a Reply

Your email address will not be published.

Back to top button