Revise tax classification for international customers of the company in WooCommerce

I am currently facing an issue in WooCommerce where I need to set a different tax class for company users with billing addresses outside of Germany. Normally, the tax rate is always 19%, but in this specific case, I require it to be set at 0%. To achieve this, I have implemented the following code snippet. However, I have noticed that it only works on the checkout page. On both the thank you page and invoice, it reverts back to showing the default 19% instead of the intended 0%. My ultimate goal is to consistently apply a 0% tax class for these particular orders throughout the entire purchasing process.

function apply_conditionally_taxes() {
    if ( !is_admin() && !empty(WC()->cart->get_cart()) ) {  
        $billing_country = WC()->customer->get_billing_country();
        $post_data = isset( $_POST['post_data'] ) ? wp_unslash( $_POST['post_data'] ) : '';
        parse_str( $post_data, $parsed_data );
        $billing_company = isset( $parsed_data['billing_company'] ) ? sanitize_text_field( $parsed_data['billing_company'] ) : '';
        
        if ( !empty( $billing_company ) && $billing_country != 'DE'   ) {
            $cart_item['data']->set_tax_class( 'Online World' );
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'apply_conditionally_taxes', 99, 1 );

To provide further clarification, my setup does not involve any custom forms. Instead, I solely rely on the standard WooCommerce checkout form, particularly focusing on the billing address field. Despite the mentioned code snippet functioning correctly on the checkout page, it consistently reverts to the default tax rate whenever a user proceeds to complete their purchase.

Answer №1

You require a script to update the billing company whenever a customer makes changes to their billing information during checkout. This can easily be achieved by using an Ajax request to target any modifications made to the billing company section on the checkout page.

It is crucial to confirm that the tax rate "Online World" is correctly set as the working rate for zero-rated items, which is commonly referred to as "Zero rate" or "zero-rate" in WooCommerce. Make sure to adjust the appropriate working tax rate within the first function mentioned.

Here is the code snippet:

// Alters the tax rate conditionally for cart items
add_action( 'woocommerce_before_calculate_totals', 'alter_cart_items_tax_rate', 99, 1 );
function alter_cart_items_tax_rate( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( ! ( WC()->customer->get_billing_country() !== 'DE' && ! empty(WC()->customer->get_billing_company()) ) )
        return;

    // Define the replacement tax class here
    $company_tax_class_slug = 'zero-rate'; // or 'online-world';

    // Loop through each item in the cart
    foreach ( $cart->get_cart() as $cart_item ) {
        $cart_item['data']->set_tax_class( $company_tax_class_slug );
    }
}

// Sends an Ajax request to update the customer's billing company upon change
add_action('woocommerce_checkout_init', 'enqueue_checkout_custom_js_script');
function enqueue_checkout_custom_js_script() {
    wc_enqueue_js( "$('form.checkout').on('change', 'input[name=billing_company]', function() {
        $.ajax({
            type: 'POST',
            url: '" . admin_url('/admin-ajax.php') . "',
            data: {
                'action' : 'billing_company_update',
                'company': $(this).val()
            },
            success: function (response) {
                $(document.body).trigger('update_checkout');
            }
        });
    });" );
}

// Handles the PHP AJAX receiver and processes the ajax request
add_action('wp_ajax_billing_company_update', 'set_customer_billing_company');
add_action('wp_ajax_nopriv_billing_company_update', 'set_customer_billing_company');
function set_customer_billing_company() {
    if ( isset($_POST['company']) ) {
        $company = sanitize_text_field($_POST['company']);

        WC()->customer->set_billing_company( $company );
        WC()->customer->save();
    }
    wp_die();
}

Insert this code into the functions.php file of your child theme or create a custom plugin. It has been thoroughly tested and proven to be functional.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on utilizing ffmpeg in conjunction with PHP for file compression and uploading

Hello everyone, I have successfully installed ffmpeg on my local computer and now I'm looking to learn how to use it for uploading files via PHP to the server. My goal is to convert all user-uploaded files to SWF format. Additionally, I've increa ...

Ajax issue: unable to retrieve $_SESSION data. Works on local environment but not on web server

I've been working on a website project that involves using jQuery to interact with a database. I store the user ID in a session for updating and deleting purposes. Everything seems to be running smoothly on my localhost (Wamp server), but when I uplo ...

Sending a POST request to a Flask server using Stripe and AJAX

I am attempting to implement a function that triggers an ajax request when a stripe form is submitted. However, using the .submit() method doesn't seem to be working as expected. Here is my current code: HTML <form action="/download_data" method= ...

Send information via Ajax without relying on jQuery functions

Looking for a way to securely send a private access_token via http POST using Ajax code. Any suggestions on achieving this with the code provided below? function getstatus(url, placeid, access_token) { if(window.XMLHttpRequest) ...

Step-by-step guide on how to load an Ext JS tab after clicking on it

I have an Ext JS code block that creates 4 tabs with Javascript: var tabs; $(document).ready( function() { fullscreen: true, renderTo: 'tabs1', width:900, activeTab: 0, frame:true, ...

When working with a set of objects, consider utilizing jQuery's InArray() method to effectively handle

Within my Javascript code, I am working with an array of Calendar objects. Each Calendar object contains an array of CalendarEvent objects. Every CalendarEvent object holds properties for Date and Name. I am looking to determine if a specific date exist ...

Cheerio - Ensure accurate text retrieval for selectors that produce multiple results

Visit this link for more information https://i.stack.imgur.com/FfYeg.png I am trying to extract specific market data from the given webpage. Specifically, I need to retrieve "Sábado, 14 de Abril de 2018" and "16:00". Here is how I did it using Kotlin an ...

Getting a file in php: a step-by-step guide

My PHP function is meant for downloading an encrypted file after processing the data The Connect Class is used for database connection class License extends Connect { function __construct() { parent::__construct(); } public func ...

What's causing this error with jQuery and JSON?

When utilizing the following code snippet: - $.getJSON("admin.php?format=json", { module: "data", action: "allBusinessUnitsByClientName", clientname : $('#client').val() }, function(json) { $.each(json.items, function(i,item){ alert ...

Generate dynamic lines with evolving hues using CSS3

While working on a fresh web project, I came across the need to emphasize my headers (h1, h2, h3, h4) with underlines. My goal is to have these underlines grow and change color dynamically, similar to what can be seen here: . Is there a way to achieve thi ...

A step-by-step guide to integrating cloud computing and creating tokens using PHP

I am looking to create a cloud computing project using PHP. The main goal of this project is for users to store their files on a cloud server and if any unauthorized manipulations occur, the system should be able to detect and correct them. My question is ...

How about this: "Unveil the beauty of dynamically loaded

var request = new Request({ method: 'get', url: 'onlinestatusoutput.html.php', onComplete:function(response) { $('ajax-content').get('tween', {property: 'opacity', duration: 'long&apos ...

Share a model between two partial views within the same view

I'm facing an issue with loading two partial views in my main view. The main view is set to automatically refresh partial view 1, while partial view 2 should only update when a user clicks on an Ajax.ActionLink from partial view 1. This click event sh ...

Is verifying email and password with jquery possible?

I am currently working on a jQuery form validation project: While the password and username validation are working fine, I am facing issues with email and password confirmation validations. Surprisingly, I have used the same technique for both. If you wa ...

Encountering issues with loading the database on the Android application

My challenge lies in using a single database for both an Android application and a website. This setup allows the admin to update the website and app simultaneously through one admin panel. The database, which consists of 15 tables, presents a roadblock ...

Is it possible for a submission of a form to modify the content length header, resulting in the request failing?

Issue Description: After binding a submit event to an AJAX post request in order to send a predetermined key-value pair to a PHP script, the expected message indicating successful communication is not received. Despite the fact that the submit event trig ...

Is it possible to use both the .load function and fadeIn in jQuery simultaneously?

Currently, I am utilizing the .load method to bring in another page using jQuery. Below is the code snippet: $('#page1').click(function(){ $("#content").load("page1.html"); }); While this code works well, I am inte ...

Begin by utilizing the variables published

I have a form on my website that submits data using ajax, allowing for seamless interaction without page refresh. After the form is submitted, I want to dynamically display the user's input by inserting it at the top of the content. However, I am uns ...

Choosing the right jQuery selector to target a section that contains div elements

Whenever the h2 element within a section is clicked, I want all the fields in that section to be displayed. For example, if the user clicks on 'Contact Information', the three form inputs (fields) below the Contact Information heading should appe ...

PHP email sending functionality is malfunctioning

Please fill in the following details: Full Name ...