How to add rel="canonical" link to section of Page



The issue I was facing was the page rel="canonical" links were redirecting to a 404 page.

My rel canonical for page was "http://example.com/2/" instead of "http://example.com/page/2/" So I edited the rel canonical function in this file *wp-includes/link-template.php this file

function rel_canonical() {
  if ( ! is_singular() ) {
    return;
 }

 if ( ! $id = get_queried_object_id() ) {
    return;
 }

 $url = get_permalink( $id );

  $page = get_query_var( 'page' );
  if ( $page >= 2 ) {
   if ( 'page' == get_option( 'permalink_structure' ) ) {
      $url = add_query_arg( 'page', $page, $url );
    } else {
      $url = trailingslashit( $url ) . user_trailingslashit( $page, 'single_paged' );
   }
 }

 $cpage = get_query_var( 'cpage' );
  if ( $cpage ) {
   $url = get_comments_pagenum_link( $cpage );
 }
     echo '<link rel="canonical" href="' . esc_url( $url ) . "\" />\n";
}

I hard coded the home page url here for SEO and so now my page rank will flow to the home page now

$url = trailingslashit( http://example.com/ )

*for posts the rel="canonical" was working fine.


Hi Venkatesh,

You should definitely not make modification in WordPress Core files (Beans Core neither in fact) as it will be overwritten next time you update it. If you want to modify the WordPress Core rel_canonical(), you can do so by removing the action and re-add it with your own callback as follow:

// Remove WP Core action.
remove_action( 'wp_head', 'rel_canonical' );

// Add your own action callback.
add_action( 'wp_head', 'example_rel_canonical' );

function example_rel_canonical() {
 // Your modified code.
}

Hope that helps,


Thanks Thierry Muller for letting me know about that. I will remove the changes which I did and start using the child's functions.php

Write a reply

Login or register to write a reply, it's free!