Customize rel=canonical tag for single blog post

I wrote a guest blog post for another website. I'd like to publish this same blog post on my website but include a canonical URL that points to the original publisher.

This allows me to post the article on my website while notifying Search Engines of the canonical location of the post and avoiding SEO penalties.

In the wp_head action, WordPress prints a rel=canonical tag automatically and places it in the head for posts.

I tried to use a snippet of code to output my own rel=canonical (possibly compounding the already automatically output one) with:

?php if ( is_single('1234') ) echo 'link rel="canonical" href="https://www.examplesite.com/my-guest-post" /'; ?

Upon inspection, this code never prints to the page. I imagine it might have to do with parse order.

Does anyone know how I might correctly implement this? I don't want to mess with the WordPress native code too much but would like to find a simple mechanism that lets me alter the rel=canonical meta tag on a per post basis.

I do not want to use Yoast.

Thanks in advance,

Topic rel-canonical post-meta custom-field posts customization Wordpress

Category Web


Or to add them for all pages, except the homepage:

        <?php
           if ( is_front_page() ) {
              $canonical_url = get_home_url();
           } else {
              $canonical_url = get_permalink();
           }
        ?>
        <link rel="canonical" href="<?php echo $canonical_url ?>" />

Upon inspection, this code never prints to the page. I imagine it might have to do with parse order.

It depends where you added it. If you want to add code to the <head> element of the page you either need to put it in that element in the head in the header.php template or in your theme's functions.php file or a plugin with a hook. Pasting just that code in functions.php naked (without a hook or function definition) will cause WordPress to output it before the page has even started being output, which can result in errors.

Regardless, in this case WordPress offers a filter hook, get_canonical_url which can be used to change the URL used in the canonical header added by WordPress.

Use it like this:

function wpse_302620_canonical_url( $canonical_url, $post ) {
    if ( $post->ID === 1234 ) {
        $canonical_url = 'https://www.examplesite.com/my-guest-post';
    } 

    return $canonical_url;
}
add_filter( 'get_canonical_url', 'wpse_302620_canonical_url', 10, 2 );

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.