Silverstripe Canonical URL

posted by Matt Adams

Canonical URLs can be useful for SEO. Silverstripe does not include these by default so I’m going to show you 2 ways to add a Silverstripe canonical URL to your site.

Method 1

The most logical approach in my opinion, simply pull the url into our SS template. Do this by copying the following function into your Page_Controller class.

function CanonicalURL() {
   return Director::protocolAndHost() . $this->Link();
}

Then copy the following into the head of your SS template.

<link rel="canonical" href="$CanonicalURL">

Method 2

This method makes use of Silverstripe’s MetaTags function. If you havent already, you will need to copy the MetaTags function located in sapphire/core/model/SiteTree.php and paste it into your Page_Controller class. This will override the function found in SiteTree.php so that your not editing core files. Start by pasting the following line of code into the MetaTags function in your Page_Controller.

$tags .= "AbsoluteLink() . $this->GetCanonical() . "\">";

Then copy the following into your Page_Controller class.

function GetCanonical() {
   if (Director::urlParam('Action')) {
      $action = Director::urlParam('Action');
      $parameterID = urlencode(Director::urlParam('ID'));
      $parameterOtherID = urlencode(Director::urlParam('OtherID'));
      if (strcmp($action, $this->URLSegment) == 0 && empty($parameterID) ) {
         return false;
      } else if (strcmp($parameterID, $this->URLSegment) == 0) {
         return false;
      } else if (strcmp($action, $this->URLSegment) != 0 && empty($parameterOtherID)){
         return $action . '/' . $parameterID;
      } else {
         return $parameterID . '/' . $parameterOtherID;
      }
   }
}

That’s it! 2 methods for adding a canonical url to your Silverstripe site.