diff --git a/CHANGELOG.md b/CHANGELOG.md index 4afdbcb..45fd3b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,9 @@ # Changelog -## 2.2.0 - 2020-05-19 +## 2.2.0 - UNRELEASED ### Added -- Added fallback link to homepage when entry is not found on target site +- Optionally fall back to the translated homepage when a link cannot otherwise be determined. ## 2.1.0 - 2019-04-20 diff --git a/README.md b/README.md index 6ebe361..cdd9357 100644 --- a/README.md +++ b/README.md @@ -110,9 +110,11 @@ You can check to make sure that a translated version of that element exists befo ``` -### Checking whether a translated element exists +### Fall back to the translated homepage + +Assuming your homepage is properly translated across each site, you can set the homepage as a final backstop. If the link cannot otherwise be determined, it will link to the translated homepage instead. -Lastly, you can add a fallback to show a link to the homepage of the target site if the entry does not exist on the target site by setting the third parameter to true: +Simply set the optional third parameter to `true`: ```twig {% set element = (category ?? entry ?? null) %} diff --git a/src/services/SiteSwitcherService.php b/src/services/SiteSwitcherService.php index 10d3886..6a92490 100644 --- a/src/services/SiteSwitcherService.php +++ b/src/services/SiteSwitcherService.php @@ -39,9 +39,12 @@ class SiteSwitcherService extends Component */ public function url($siteHandle = null, Element $element = null, bool $fallbackToHomepage = false) { + // Get sites service + $sites = Craft::$app->getSites(); + // If no site handle specified, use the default site if (!$siteHandle) { - $siteHandle = Craft::$app->getSites()->getPrimarySite()->handle; + $siteHandle = $sites->getPrimarySite()->handle; } // If element is specified @@ -61,9 +64,9 @@ public function url($siteHandle = null, Element $element = null, bool $fallbackT $siteLink .= "?{$queryString}"; } - // If not element is found on the target site, fallback to homepage - if ($siteLink === false && $fallbackToHomepage === true) { - $siteLink = Craft::$app->getSites()->getSiteByHandle($siteHandle)->getBaseUrl(); + // If site link isn't valid, optionally fall back to the homepage + if (!$siteLink && $fallbackToHomepage) { + $siteLink = ($sites->getSiteByHandle($siteHandle)->getBaseUrl() ?? false); } // Return site link