From 25aadd43106d5cec35370498e9796176829cc2b6 Mon Sep 17 00:00:00 2001 From: Tim Burt Date: Wed, 20 Jun 2018 17:14:22 +0100 Subject: [PATCH] Move extension to Page Add rules to YML to try and be last in line Add checking on existing tags to attempt to remove existing canonical tags --- _config/config.yml | 4 ++- src/SiteTreeCanonicalExtension.php | 52 +++++++++++++++++++----------- 2 files changed, 36 insertions(+), 20 deletions(-) diff --git a/_config/config.yml b/_config/config.yml index 0449647..07529c9 100644 --- a/_config/config.yml +++ b/_config/config.yml @@ -1,7 +1,9 @@ --- Name: 'dd-canonical' +After: + - '*' --- -SilverStripe\CMS\Model\SiteTree: +Page: extensions: - DorsetDigital\SilverStripeCanonical\SiteTreeCanonicalExtension diff --git a/src/SiteTreeCanonicalExtension.php b/src/SiteTreeCanonicalExtension.php index 0638672..6992692 100644 --- a/src/SiteTreeCanonicalExtension.php +++ b/src/SiteTreeCanonicalExtension.php @@ -8,23 +8,37 @@ class SiteTreeCanonicalExtension extends SiteTreeExtension { - public function MetaTags(&$tags) - { - - $siteConfig = SiteConfig::current_site_config(); - if ($siteConfig->CanonicalDomain != '') { - $canonicalBase = trim($siteConfig->CanonicalDomain, '/'); - if (method_exists($this->owner, 'CanonicalLink')) { - $link = $this->owner->CanonicalLink(); - } else { - $link = $this->owner->Link(); - } - $canonLink = $canonicalBase . $link; - $atts = [ - 'rel' => 'canonical', - 'href' => $canonLink - ]; - $tags .= "\n" . HTML::createTag('link', $atts) . "\n"; - } - } + public function MetaTags(&$tags) + { + + $siteConfig = SiteConfig::current_site_config(); + if ($siteConfig->CanonicalDomain != '') { + $canonicalBase = trim($siteConfig->CanonicalDomain, '/'); + if (method_exists($this->owner, 'CanonicalLink')) { + $link = $this->owner->CanonicalLink(); + } else { + $link = $this->owner->Link(); + } + $canonLink = $canonicalBase . $link; + $atts = [ + 'rel' => 'canonical', + 'href' => $canonLink + ]; + $canonTag = HTML::createTag('link', $atts); + + $tagsArray = explode(PHP_EOL, $tags); + $tagPattern = 'rel="canonical"'; + + $tagSearch = function ( $val ) use ( $tagPattern ) { + return ( stripos($val, $tagPattern) !== false ? true : false ); + }; + + $currentTags = array_filter($tagsArray, $tagSearch); + $cleanedTags = array_diff($tagsArray, $currentTags); + + $cleanedTags[] = $canonTag; + + $tags = implode(PHP_EOL, $cleanedTags); + } + } }