Passing the parameter through the REST API and executing ADD_FILTER in Wordpress

103 views Asked by At

I'm programming a currency change based on the current language of the site. I use plugins: GTranslate (free) and WooCommerce Multilingual & Multicurrency (also free version). Using a JS script, I retrieve the "lang" attribute from the tag (it is set by the GTranslate plugin when changing the language). Then, using the REST API, I send the language code to functions.php. There I do ADD_FILTER and change the current currency in Woocommmerce. The problem is that the currency does not change, despite the fact that PHP receives the correct data from JS.

Here is the JS code. For simplicity, I send a constant value.

const myParam = 'en_US';

    $.ajax({
        url: '/wp-json/myplugin/v1/myfunction/' + myParam,
        method: 'POST',
        dataType: 'json',
        success: function(response) {
            console.log('Odpowiedź z funkcji:', response);
        },
        error: function(xhr, status, error) {
            console.error('Wystąpił błąd AJAX:', error);
        }
    });

This is functions.php:

add_action('rest_api_init', 'register_custom_endpoint');

function register_custom_endpoint() {
    register_rest_route('myplugin/v1', '/myfunction/(?P<param>\w+)', array(
        'methods'  => 'POST',
        'callback' => 'my_custom_function',
    ));
}


function my_custom_function($request) {
    
    $param = $request->get_param('param');
    if ($param == "en_US") {
        changeCurrency();
    }

    $response = array(
        'message' => 'Funkcja została wywołana pomyślnie z parametrem: ' . $param
    );
    return wp_send_json($response);
}

function changeCurrency() {
    add_filter('wcml_client_currency', 'wcml_custom_currency');
    function wcml_custom_currency($current){
        return 'USD';
    }
}

The "param" variable takes the correct value. But the "changeCurrency" function doesn't work. I also checked outside of the "if" condition, but to no avail.

If I call the "changeCurrency" function like this:

changeCurrency();
function changeCurrency() {
    add_filter('wcml_client_currency', 'wcml_custom_currency');
    function wcml_custom_currency($current){
        return 'USD';
    }
}

it works fine.

0

There are 0 answers