Using K2 Extra fields to add a rel=”canonical” to your page

You can insert rel canonical links using K2’s extra fields feature. But how? We’ll help you get going here in a second! We recently decided to have some content move from our blog to our tutorial/support page. We didn’t want to lose the link juice, but also wanted to make sure that we didn’t have duplicate content. Since there isn’t a way to add canonicals from K2 or Joomla native, we created this system.

Create an Extra Field Group and Canonical Extra Field

You should first create and assign an appropriate extra fields group and an extra field to your category. You can read about general K2 extra fields use here: K2 Extra Fields. Make sure that extra fields is set to visible for your items!

Let’s assume in this article that you called your extra field “canonical”.

Once you’ve created and assigned your extra field to your category we need to modify your “item.php” file. You should add the code below to the top of your “item.php” file (inside a <?php ?>) for your current k2 theme.  If you don’t know how to theme K2, view the’s tutorial on templating with K2.

if($this->item->params->get('itemExtraFields') && count($this->item->extra_fields)){ 	foreach ($this->item->extra_fields as $key=>$extraField) { 		if($extraField->value != '') { 			switch($extraField->name) { 				case 'canonical': 					$rel_canonical = '<link rel="canonical" href="'.$extraField->value.'"/>'; 					$doc = & JFactory::getDocument(); 					$doc->addCustomTag($rel_canonical); 				break; 			} 		} 	} }  

This will detect the extra field “canonical” and insert the link into the Joomla head.

Hope this helps!