Skip to content

Commit

Permalink
Move extension to Page
Browse files Browse the repository at this point in the history
Add rules to YML to try and be last in line
Add checking on existing tags to attempt to remove existing canonical tags
  • Loading branch information
DorsetDigital committed Jun 20, 2018
1 parent a965361 commit 25aadd4
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 20 deletions.
4 changes: 3 additions & 1 deletion _config/config.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
---
Name: 'dd-canonical'
After:
- '*'
---
SilverStripe\CMS\Model\SiteTree:
Page:
extensions:
- DorsetDigital\SilverStripeCanonical\SiteTreeCanonicalExtension

Expand Down
52 changes: 33 additions & 19 deletions src/SiteTreeCanonicalExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}

0 comments on commit 25aadd4

Please sign in to comment.