Skip to content

Instantly share code, notes, and snippets.

@bartwttewaall
Created January 4, 2024 15:54
Show Gist options
  • Save bartwttewaall/4e1d054330ee6b16b86aca147bfc015a to your computer and use it in GitHub Desktop.
Save bartwttewaall/4e1d054330ee6b16b86aca147bfc015a to your computer and use it in GitHub Desktop.
Alternate content links
{# Include in the head of the base page template #}
{% set currentElement = craft.app.urlManager.matchedElement %}
{% set sites = craft.app.getSites().getGroupById(currentSite.groupId).getSites()|filter(s => s.baseUrl is not empty) %}
{% set altLinks = [] %}
{% for site in sites %}
{% set title = craft.app.i18n.getLocaleById(site.language).displayName %}
{% set url = site.getBaseUrl() %}
{% if currentElement %}
{% set otherLocaleElement = craft.app.getElements().getElementById(currentElement.id, currentElement.className(), site.id) %}
{% if otherLocaleElement and otherLocaleElement.enabledForSite %}
{% set url = otherLocaleElement.url %}
{% endif %}
{% endif %}
{% set altLinks = altLinks|merge([{
url: url,
title: title,
countryCode: site.language|split('-')|last,
current: site.id == currentSite.id ? true : false,
language: site.language,
}]) %}
{% endfor %}
{% if altLinks|length > 1 %}
{% for altLink in altLinks %}
<link rel="alternate" href="{{ altLink.url }}" hreflang="{{ altLink.language }}" />
{% endfor %}
{% endif %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment