0

I'm trying to set up a select box which allows my site visitors to change the tax rate that they need to pay in WooCommerce (version 3.6.4).

I've set up a custom plugin which detects if they've changed the tax rate, then updates the tax class used. This is persisted by use of an additional cookie. It's working well, however, in two areas, the price is always out of date on a page reload.

On the basket page, they see a form (with just a select and a submit button) if they submit the form, this POSTs to the same URL and sets the cookie and the tax class by using a couple of filters. Here's the code doing this (a little messy, and verbose, granted):

<?php

namespace Example;

class TaxRate
{
    public function __construct()
    {
        //$this->setCookie();

        $this->addActions();

        $this->addFilters();
    }

    private function addActions()
    {
        add_action("init", [$this, 'setCookie']);
    }

    public function setCookie()
    {
        if($_POST['tax-rate'] == "wholesale")
        {
            setcookie("tax-rate", "wholesale", time() + (86400 * 365), "/");

            $_COOKIE['tax-rate'] = "wholesale";
        }
        else if($_POST['tax-rate'] == "standard")
        {
            setcookie("tax-rate", "standard", time() + (86400 * 365), "/");

            $_COOKIE['tax-rate'] = "standard";
        }
        else if(!isset($_COOKIE['tax-rate']))
        {
            setcookie("tax-rate", "standard", time() + (86400 * 365), "/");

            $_COOKIE['tax-rate'] = "standard";
        }
    }

    private function addFilters()
    {
        add_filter("woocommerce_product_get_tax_class", [$this, 'setTaxRate'], 1, 2);
        add_filter("woocommerce_product_variation_get_tax_class", [$this, 'setTaxRate'], 1, 2);
    }

    public function setTaxRate($tax_class, $product)
    {
        if($_COOKIE['tax-rate'] == "wholesale")
        {
            return "Wholesale";
        }

        return "";
    }
}

When the basket/cart page reloads, the prices in the table are updated. However, in the header, we have the subtotal displayed but this displays the old amount (using the standard tax class). If I refresh the page or load it again, the new amount (using the selected tax class) displays.

I can't figure out why this is the case although I'm suspecting it's down to the cookie and the use of the filters that get the tax class. Also, after a little digging, the cart total in the header looks to use the get_cart_subtotal in the WC_Cart class.

Thanks in advance!

closed as off-topic by fuxia Aug 15 at 23:05

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

Browse other questions tagged or ask your own question.