gnome-search-tool

Canonical URLs revisited

To prevent indexing errors because of duplicate titles or duplicate content you can specify a canonical page to search engines by adding a <link> element with the attribute rel="canonical" to the <head> section of the non-canonical version of the page.

WordPress adds this link, in the function rel_canonical(), found in link_template.php this function echoes the <link>. The function returns the permalink for the page or post, which is not good for our galleries. We want to have this canonical url point to the individual folders and images. Bad thing is that here is no filter to change to canonical page. We have to override this function. Below is some code you may add to your theme functions.php to accomplish this.

If you are using Lazyest Gallery version 1.1 or higher, please read the updated post.

Warning! If you use an SEO plugin like WordPress SEO by Yoast (and I believe you should), do not use this method, but apply a filter as described in my post about Lazyest Gallery and SEO plugins

 
//first remove the wordpress canonical action
remove_action('wp_head', 'rel_canonical');
 
function my_gallery_canonical() {
  global $lg_gallery, $wp_the_query, $lg_offset, $lg_diroffset;
  // this is copied from original wordpress code   
  if ( !is_singular() )
    return;
  if ( !$id = $wp_the_query->get_queried_object_id() )
    return;
  $link = get_permalink( $id );
  // check if lazyest gallery is activated    
  if ( isset( $lg_gallery ) ) { 
    // check if this is the actual gallery page
    if ( $lg_gallery->is_gallery() ) {
      // validate and clean up the gallery query 
      $lg_gallery->valid();
      // the base link is our gallery page link 
      // as given in lazyest gallery settings
      $link = trailingslashit( $lg_gallery->get_option( 'gallery_prev' ) );
      // check if we are displaying a folder or image
      if ( isset( $lg_gallery->file ) ) {
        // compile canonical link 
        if ( 'TRUE' != $lg_gallery->get_option('use_permalinks') ) {      
          $link = add_query_arg( 'file', $lg_gallery->file, $link );  
        } else {
          $link .= $lg_gallery->file;
        }      
        $link = trailingslashit( $link );    
      }
    } 
    // pages should also be indexed
    if ( isset( $lg_offset ) ) {
      if ( $lg_offset != 0 )
        $link = add_query_arg( 'lg_offset', $lg_offset, $link );
    }	 
    if ( isset( $lg_diroffset) ){
      if ( $lg_diroffset != 0 )
        $link = add_query_arg( 'lg_diroffset', $lg_diroffset, $link );
    }  
  }  
  echo "<link rel='canonical' href='$link' />\n";
}
 
// add our canonical function to the head element
add_action('wp_head', my_gallery_canonical );
 

2 thoughts on “Canonical URLs revisited

  1. Pingback: Fixing duplicate title tags for Lazyest Gallery, a WordPress plugin | Brimosoft

Comments are closed.