WPCS - WordPress Currency Switcher Professional

Show content based on the selected currency in WordPress

To show content based on the selected currency in WordPress, for example a payment note only for visitors who pay in US dollars, a different order link for each currency, or a disclaimer for everyone who is not looking at the base currency, your code needs to know which currency the visitor has chosen. WPCS keeps it in one PHP property and repeats it in a class on the <body> tag and in a JavaScript variable. Below is how to use each of them, how to pass the selected currency into links, and what changes when the site runs a page cache.

Where WPCS keeps the selected currency

The plugin creates one global object, $WPCS. Two of its properties matter here:

The current currency is the visitor's last choice in the switcher or in a ?currency=EUR link, or, on the first visit, the welcome currency or a GeoIP rule. The plugin stores it per visitor (the Currency storage option: transient, session or cookie) and reads it on every page load. GeoIP rules are applied on the WordPress init hook, so read the property in a shortcode, a template or a hook that runs after init, not at the top level of functions.php.

The same value reaches the front end in two more places:

WhereValue when EUR is selectedGood for
$WPCS->current_currency in PHPEURShortcodes and theme templates
Class on the <body> tagcurrency-eur (lower case)Showing and hiding blocks with CSS
JavaScript variable wpcs_current_currencyan object, wpcs_current_currency.name is EURYour own scripts

Always compare the property, not the object. A condition like if ($WPCS == 'USD') compares the whole plugin object with a string and is never true, so the content never appears. The correct form is if ($WPCS->current_currency === 'USD').

Show content based on the selected currency with a shortcode

For a sentence, a note or a link inside a page, an enclosing shortcode is the most convenient: the editor wraps the text, and visitors with another currency do not receive it at all. Register it once:

/*
 * Child theme functions.php or a code snippets plugin.
 * [show_for_currency currency="USD"]...[/show_for_currency]      only for USD
 * [show_for_currency currency="USD,CAD"]...[/show_for_currency]  for USD or CAD
 * [show_for_currency not="USD"]...[/show_for_currency]           for every currency except USD
 */
add_shortcode('show_for_currency', function ($atts, $content = '') {
    global $WPCS;
    if (empty($WPCS)) {
        return '';
    }

    $atts = shortcode_atts(array('currency' => '', 'not' => ''), $atts, 'show_for_currency');
    $current = strtoupper($WPCS->current_currency);
    $only = array_filter(array_map('trim', explode(',', strtoupper($atts['currency']))));
    $except = array_filter(array_map('trim', explode(',', strtoupper($atts['not']))));

    if ($only && !in_array($current, $only, true)) {
        return '';
    }
    if ($except && in_array($current, $except, true)) {
        return '';
    }

    return do_shortcode((string) $content);
});

Then use it in the content:

[show_for_currency currency="USD"]American Express cards are accepted.[/show_for_currency]

[show_for_currency not="USD"]Prices in your currency are approximate. Payment is taken in US dollars.[/show_for_currency]

Shortcodes inside, such as [wpcs_price], keep working because the content passes through do_shortcode(). Currency codes are compared in upper case, so currency="usd" works as well.

In a theme template, use the same check directly:

<?php
// A template file of your child theme
global $WPCS;
if (!empty($WPCS) && $WPCS->current_currency === 'USD') : ?>
    <p class="payment-note">American Express cards are accepted.</p>
<?php endif; ?>

Show or hide whole blocks with CSS classes

When a whole group of blocks, a section of a page builder or a widget depends on the currency, wrapping it in a shortcode is awkward. Use the body class instead. WPCS adds currency- plus the lower-case code to the <body> tag through the standard body_class filter, so any theme that prints body_class() gets currency-usd, currency-eur and so on.

  1. Give the block a class: in the block editor open the block settings, Advanced → Additional CSS class(es), and type only-usd (show only for USD) or hide-usd (hide for USD). Page builders have the same field, in Elementor it is Advanced → CSS Classes.
  2. Add the rules once, one line per currency you use:
/* Appearance → Customize → Additional CSS (Styles → Additional CSS in a block theme) */
body:not(.currency-usd) .only-usd,
body:not(.currency-eur) .only-eur,
body.currency-usd .hide-usd {
    display: none !important;
}

The difference from the shortcode: the hidden block is still in the page source, only not displayed. That is fine for notes, banners and buttons, but not for anything that must stay private, such as a discount code for one market.

Print the current currency: [wpcs_current_currency]

To tell visitors which currency they see, the plugin has its own shortcode, [wpcs_current_currency]. By default it prints Current currency is:, the code and the currency's flag. Its attributes:

AttributeDefaultWhat it does
textCurrent currency is:The text before the code. text="none" prints no text
code10 hides the currency code
flag10 hides the flag. Set it to 0 if your currencies have no flag images, otherwise an empty image is printed
currencythe selected currencyShows the given currency instead, for example currency="EUR". It must be one of your currencies

Example: [wpcs_current_currency text="Prices are shown in" flag=0]. The output is wrapped in <span class="wpcs_current_currency wpcs_current_currency_EUR">, with the parts in .wpcs_current_currency_text, .wpcs_current_currency_code and .wpcs_current_currency_flag, so you can style the label per currency, for example .wpcs_current_currency_EUR .wpcs_current_currency_code { color: #1e5aa8; }. For the bare code without markup, see how to display the current currency code.

Pass the selected currency into links

Any page address with ?currency= and a code switches the visitor to that currency and the plugin remembers it, as described in a different currency on different pages. Links between pages of your own site do not need the parameter: the stored choice already applies everywhere. You need it when the link leaves that storage, for example a booking form, an order page or another site that reads the currency from the address.

This shortcode returns any URL with the visitor's currency added, but only when it is not the base currency. Links for base-currency visitors stay identical to the plain URL, which keeps them cacheable and avoids duplicate addresses:

/*
 * Child theme functions.php or a code snippets plugin.
 * [current_currency_url url="https://booking.example.com/form/"]
 * returns https://booking.example.com/form/?currency=EUR for a visitor in EUR,
 * and the URL unchanged for a visitor in the base currency.
 */
add_shortcode('current_currency_url', function ($atts) {
    global $WPCS;
    $atts = shortcode_atts(array('url' => home_url('/')), $atts, 'current_currency_url');
    $url = $atts['url'];

    if (!empty($WPCS) && $WPCS->current_currency !== $WPCS->default_currency) {
        $url = add_query_arg('currency', $WPCS->current_currency, $url);
    }

    return esc_url($url);
});

add_query_arg() adds & or ? as needed and replaces an existing currency parameter. WordPress runs shortcodes inside quoted HTML attributes, so the shortcode can be the link address in a Custom HTML block or in the classic editor. Use single quotes inside it, because the href uses double quotes:

<a class="button" href="[current_currency_url url='https://booking.example.com/form/']">Book now</a>

Link fields of the block editor and of page builders usually do not run shortcodes. For those links, use the wpcs-currency-link class from the next section.

If the target expects different parameters for each currency rather than a currency parameter, for example a form that preselects a different option per market, write one link per currency inside [show_for_currency]:

[show_for_currency currency="USD"]<a href="https://forms.example.com/order?plan=us">Order now</a>[/show_for_currency]
[show_for_currency currency="EUR,GBP"]<a href="https://forms.example.com/order?plan=eu">Order now</a>[/show_for_currency]
[show_for_currency not="USD,EUR,GBP"]<a href="https://forms.example.com/order">Order now</a>[/show_for_currency]

Pages served from a cache: switch content in the browser

Everything printed by PHP, the shortcodes above included, becomes part of the HTML that a page cache stores. The next visitors receive that copy and see the content chosen for the visitor who filled the cache, whatever their own currency. The body class and the wpcs_current_currency variable are cached with it.

There are two ways out. Exclude the pages with currency-dependent content from the page cache; then PHP runs for every visitor and nothing else is needed. Or let the browser correct the page. With I am using cache plugin on my site set to Yes in Settings → Currency Switcher → Options, the plugin sends one request with action=wpcs_get_prices_html after each page load to redraw the prices, and the answer contains the visitor's real currency in current_currency. This snippet listens to that answer, sets the body class again and updates links that carry the wpcs-currency-link class (on the link itself or on its wrapper, as with Button blocks):

/*
 * Child theme functions.php or a code snippets plugin.
 * Keeps the body class currency-xxx and links with the class wpcs-currency-link
 * in step with the visitor's currency, on cached pages too.
 */
add_action('wp_footer', function () {
    ?>
    <script>
    (function ($) {
        function applyCurrency(code) {
            if (!code) {
                return;
            }
            code = String(code);
            var body = $('body');
            $.each((body.attr('class') || '').split(/\s+/), function (i, cls) {
                if (cls.indexOf('currency-') === 0) {
                    body.removeClass(cls);
                }
            });
            body.addClass('currency-' + code.toLowerCase());

            var base = (typeof wpcs_default_currency !== 'undefined') ? wpcs_default_currency.name : '';
            $('a.wpcs-currency-link, .wpcs-currency-link a').each(function () {
                if (!this.getAttribute('href')) {
                    return;
                }
                var url = new URL(this.href, window.location.href);
                if (code === base) {
                    url.searchParams.delete('currency');
                } else {
                    url.searchParams.set('currency', code);
                }
                this.href = url.toString();
            });
        }

        // the currency the page was built for
        $(function () {
            if (typeof wpcs_current_currency !== 'undefined' && wpcs_current_currency) {
                applyCurrency(wpcs_current_currency.name);
            }
        });

        // the visitor's real currency, from the plugin's request on cached pages
        $(document).on('ajaxSuccess', function (event, xhr, settings) {
            if (typeof settings.data !== 'string' || settings.data.indexOf('action=wpcs_get_prices_html') === -1) {
                return;
            }
            try {
                applyCurrency(JSON.parse(xhr.responseText).current_currency);
            } catch (e) {}
        });
    })(jQuery);
    </script>
    <?php
}, 100);

With it, the CSS class method works on cached pages: the right blocks appear a moment after the page loads, once the answer arrives. The enclosing shortcode cannot be corrected this way, because the other currencies' content was never sent to the browser, so on cached pages use CSS classes or exclude the page. The plugin skips its request on addresses that already contain ?currency=; such addresses are built for that currency anyway. If you delay JavaScript with an optimization plugin, the snippet has to run undelayed, just like the switcher; the exclusions are listed in currency switcher not working with a cache plugin.

If it does not work

  • The shortcode text appears on the page. The snippet is not active, or the field does not run shortcodes. Test it in a plain paragraph of a page first.
  • Nothing changes when you switch currency. Open the page source and look for currency- in the <body class= line. If it is missing, the theme does not call body_class(); if it shows the old currency while you are logged out, the page comes from a cache.
  • Works for you, not for visitors. Page caches usually skip logged-in administrators. Test in a private window after clearing every cache layer.
  • A PHP condition never matches. Compare $WPCS->current_currency, not $WPCS, use the code exactly as in the Currencies tab, and run the check after init.
  • The link loses the currency. Check that the visitor's currency is not the base one: [current_currency_url] and the snippet deliberately leave base-currency links without the parameter.

If the content still does not follow the selected currency, open a topic on the WPCS support forum with the page link, the code you added and whether a cache or optimization plugin is active.