Adding rel=canonical meta tags to your gallery

ichthyous

Joined: 2006-06-16
Posts: 324
Posted: Wed, 2012-10-03 00:00

If anyone wants to use canonical url meta tags on their pages I am posting a bit of code that Wayne (Suprsidr) worked out for me for my site. It pulls the url for the current page and fills in the meta tag with the current page url:

Quote:
{if isset($theme.currentPage) && $theme.currentPage != 1}
{php}$this->_tpl_vars['theme']['pageUrl']['page'] = $this->_tpl_vars['theme']['currentPage'];{/php}
{/if}
<link rel="canonical" href="{g->url params=$theme.pageUrl forceFullUrl=true forceSessionId=false}" />

This should be placed in the head of the page along with the other meta tags. The canonical url tag is used to specify the correct url for the page for search engine purposes. It reduces duplicate content errors in Google, when multiple versions of the same page are indexed, for example pages with dynamic session ID or nav IDs. Use this code with care, it basically instructs the search engines to drop other versions of the page other than the 'canonical' version. This code is tested and was working on both our sites, so it's complete. Thanks to Wayne for working this out.

 
Dayo

Joined: 2005-11-04
Posts: 1642
Posted: Fri, 2012-10-12 09:15

This is very cool.

One suggestion, to do this "properly", is to handle this in theme.inc instead of theme.tpl.

To do this, add a new function to the theme.inc file. A good place is just before the last closing brace for the theme's class (at page bottom).

/**
* Function to add canonical URLs
* 
* @See: http://gallery.menalto.com/node/108942
*/
function addCanonicalURL(&$template) {
	// load the theme item object
	$theme =& $template->getVariableByReference('theme');

	// append 'g2_page' argument if not first/only page of a theme item 
	if (isset($theme['currentPage']) && $theme['currentPage'] != 1) {
		$theme['pageUrl']['page'] = $theme['currentPage'];
	}
	
	// get the theme item's canonical url 
	$CanonicalURL = GalleryTemplateAdapter::url(
			array(
				'params' => $theme['pageUrl'], 
				'forceFullUrl' => true, 
				'forceSessionId' => false
			)
	);
	
	// add the theme item's canonical url to the page head
	$template->link(array("rel" => "canonical", "href" => $CanonicalURL));
}

Then, in the showAlbumPage, showPhotoPage and showModulePage functions, add the following just before the final "return" statements:

$this->addCanonicalURL($template);

This will make sure the whole process is properly done through the G2 framework as designed.
It also avoids using the "{php}" smarty tag which has been deprecated in favour of further separating processing from presentation.

So, for instance, if the nutcase working on updating G2's Smarty engine from Smarty2 to Smarty3 were to finish the task and the devs accept the work and roll out a G2.4 release perhaps, the original code might throw an error in such an instance.

Implemented on my sites.

--
dakanji.com