Specify custom canonical URL in WordPress Post

SEOGuy picture SEOGuy · Sep 10, 2013 · Viewed 9.4k times · Source

We operate 1000's of websites, most of them are are made for specific sports events. Currently we have our writers write to all of them specifically for unique content.

However we have 2 major sites that cover all events in their verticals; and we would like to start syndicating content to the minisites, from these major sites.

To maintain best practices in Google's eyes, we would have to specify the original source of the article via the rel=canonical tag - however our current plugin AIOSEO (All-in-One SEO) doesn't support specifying canonical tags on a post, or page basis.

Is there a way to create such a function?

Answer

Shakti Patel picture Shakti Patel · Sep 10, 2013

can you please used this code :

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

    global $wp_the_query;
    if ( !$id = $wp_the_query->get_queried_object_id() )
        return;

    $link = get_permalink( $id );
    echo "<link rel='canonical' href='$link' />\n";
}

// A copy of rel_canonical but to allow an override on a custom tag
function rel_canonical_with_custom_tag_override()
{
    if( !is_singular() )
        return;

    global $wp_the_query;
    if( !$id = $wp_the_query->get_queried_object_id() )
        return;

    // check whether the current post has content in the "canonical_url" custom field
    $canonical_url = get_post_meta( $id, 'canonical_url', true );
    if( '' != $canonical_url )
    {
        // trailing slash functions copied from http://core.trac.wordpress.org/attachment/ticket/18660/canonical.6.patch
        $link = user_trailingslashit( trailingslashit( $canonical_url ) );
    }
    else
    {
        $link = get_permalink( $id );
    }
    echo "<link rel='canonical' href='" . esc_url( $link ) . "' />\n";
}

// remove the default WordPress canonical URL function
if( function_exists( 'rel_canonical' ) )
{
    remove_action( 'wp_head', 'rel_canonical' );
}
// replace the default WordPress canonical URL function with your own
add_action( 'wp_head', 'rel_canonical_with_custom_tag_override' );