Created
April 28, 2021 12:51
-
-
Save bartwttewaall/ec68f2384db37afce0843400bfbc6ed8 to your computer and use it in GitHub Desktop.
Find the default site's entry by path, then find the entry for the current site/language and return that entry's url
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** Find primary site's entry by path and return translated variant */ | |
public function getEntryByDefaultPath($defaultPath) | |
{ | |
$primaryHandle = Craft::$app->getSites()->getPrimarySite()->handle; | |
$currentHandle = Craft::$app->getSites()->getCurrentSite()->handle; | |
$primaryEntry = \craft\elements\Entry::find()->site($primaryHandle)->uri($defaultPath)->one(); | |
if ($currentHandle == $primaryHandle) return $primaryEntry; | |
return $primaryEntry ? \craft\elements\Entry::find()->id($primaryEntry->id)->site($currentHandle)->one() : null; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{# This macro finds the default site's entry by path, then finds the entry for the current site/language and returns the correct url, | |
It solves an issue with translated paths. {{ siteUrl('account/orders') }} would result in '/de/account/orders' instead. | |
Example: | |
{% from '_macros/parts' import siteUrlByDefaultPath %} | |
<a href="{{ siteUrlByDefaultPath('account/orders') }}">{{ 'Orders'|t }}</a> | |
This would result for a German site in: <a href="/de/konto/bestellungen">Bestellungen</a> | |
The twig function {{ siteUrl('account/orders') }} would have erroneously resulted in '/de/account/orders' | |
#} | |
{% macro siteUrlByDefaultPath(defaultPath) %} | |
{% if currentSite.handle == craft.app.sites.primarySite.handle %} | |
{{ url(defaultPath) }} | |
{% else %} | |
{% set foundEntry = craft.entries.site(craft.app.sites.primarySite.handle).uri(defaultPath).one() %} | |
{% set currentSiteEntry = foundEntry ? craft.entries.id(foundEntry.id).site(currentSite.handle).one() : null %} | |
{{ currentSiteEntry ? currentSiteEntry.url : url(defaultPath) }} | |
{% endif %} | |
{% endmacro %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment