Change WooCommerce currency programmatically on AJAX request

I am adding a custom ajax_action to fetch a product and display price html (same template as everywhere else on my page), the issue is that the price being returned is not equal to the current price set by user.

In my AJAX call I have tried sending currency/wcmlc as a POST/GET parameter but this does not work.

I have also tried different actions I could find online.

I believe the problem is that the filter wcml_client_currency is not effective on AJAX requests, and this is problematic.

Using the following code:

add_filter( 'wcml_client_currency', function($current) {
    return 'DKK';
} );

Would still return EURO on AJAX requests/actions.

Topic woocommerce-offtopic ajax plugin-wpml multi-language php Wordpress

Category Web


This is how I solved it:

/**
 * Force currency change
 */

    add_filter( 'wcml_client_currency', function($current) {
        if(isset($_GET['currency']) && $_GET['currency'])
            return $_GET['currency'];

        if(isset($_POST['currency']) && $_POST['currency'])
            return $_POST['currency'];

        return $current;
    } );

And then in order for the above filter to be listened to, it's important that you have added below code:

add_action( 'wp_ajax_quick_view_single_product', __NAMESPACE__ . '\\quick_view_single_product' );
add_action( 'wp_ajax_nopriv_quick_view_single_product', __NAMESPACE__ . '\\quick_view_single_product' );

function quick_view_single_product() {

    wc_get_template('modal-single-product.php');
    die();
}

/**
 * Ensure WCML's currency filters are listened to
 */

    add_filter( 'wcml_multi_currency_ajax_actions', 'add_action_to_multi_currency_ajax', 10, 1 );

    function add_action_to_multi_currency_ajax( $ajax_actions ) {
        $ajax_actions[] =  "quick_view_single_product"; // Add a AJAX action to the array.
        return $ajax_actions;
    }

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.