1

I work on a large, complex site that uses a cookie banner to store a language cookie. We have 11 different languages on the site.

We use craft for only one part of our site, with our base URL for Craft at

/Corporate/
/Corporate/?lang=en
/Corporate/?lang=fr
/Corporate/?lang=it
...
...

Each language is set up as a separate "site", and those sites are in a group. We use Channels with entries, as well as a structure to organize the pages we have under /corporate/.

Currently we have the issue that if you are on any page other than the base URL, changing the language with our site's language selector will redirect you back to the base URL at /corporate/?lang=XX.

How can we route the language switch to stay on the current page instead of redirecting?

1 Answer 1

1

You need to modify your language switcher to redirect to the current entry with the URL appended. You can use Entry::getSupportedSites() to get an array of all sites the entry exists in. If all your sites have a different base URL, the code may look like this:

{# Get all sites this entry exists in. #}
{% set sites = entry.getSupportedSites() %}

{% for site in sites %}
    {% set site = craft.app.sites.getSiteById(site is int ? site : site.siteId) %}
    {% set is_current_site = site.id == currentSite.id %}

    {# Get the entry for this site. #}
    {% set item_entry = is_current_site ? entry : craft.entries().id(entry.id).site(site).one() %}

    {% if item_entry %}
        {# Display a link to the entry for this site. #}
        <a href="{{ url(item_entry.url) }}">{{ site.language|upper }}</a>
    {% endif %}
{% endfor %}

If you only identify the site by the URL parameter, you have to include it in the URL instead:

<a href="{{ url(item_entry.url, params={ lang: site.language }) }}">
    {{- site.language|upper -}}
</a>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.