I like this post, because I had thought about this before, but did not know where to go to customize it a little...
I had a client ask about generating Canonical URLs for their Silverstripe site....now I though to myself - with SS you don't really need Canonical URLs because the SS URLSegment is so sweet and simple. (Other CMS struggle at this with params etc)....
Anyways I had created a method in the Page class that generates the Canonical URL, and then when I saw this post, I thought why not customize the MetaTags function and have it generate it instead of putting the call in the .ss template.
So here goes some code.
1. Create a GetCanonical Method in your Page class controller (there are bunch of if/else statement to try and handle actions/IDs/OtherIDs in the NestedURL structure of 2.4)
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;
}
}
}
2. Add this simple line to your MetaTags function
$tags .= "<link rel=\"canonical\" href=\"" . $this->AbsoluteLink() . $this->GetCanonical() . "\" />\n";
This should work with simple URLs as well as accomodate the case of DataObjects being displayed with action/ID functionality. Please feel free to take it, use it, or even provide feedback on a better and more efficient means to achieve this.
- Ed