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 );