How to fix Open Graph URL not matching canonical when using Yoast SEO

on in SEO
Last modified on

Canonical vs Open Graph URL

I have recently run into an issue with the Yoast SEO plugin, as reported by an Ahrefs audit.

Basically, the Yoast SEO plugin adds an og:url Open Graph tag with a canonical URL of the page. Everything works as expected, unless you are on a paginated archive or category page. For example, take the following code:

<link rel="canonical" href="https://www.example.com/category/news/page/2/">
<link rel="prev" href="https://www.example.com/category/news/">
<link rel="next" href="https://www.example.com/category/news/page/3/">
<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="News Archives - Page 2 of 4 - My Awesome Website">
<meta property="og:description" content="See the latest news from My Awesome Website about all these awesome things.">
<meta property="og:url" content="https://www.example.com/category/news/">

Notice how the og:url is the main category page, not the actual page (2, 3 or whatever). This is the correct technical behaviour, but it’s not always the right one for our technical SEO. Yoast’s method doesn’t check if the current page (archive, category, or taxonomy) is paginated or not:

WPSEO_Frontend::get_instance()->canonical(false, true);

So we need to hook into this method and add the current page (if any). The code below checks if a variable called paged exists and then appends it to the current canonical URL:

function gb_wpseo_canonical( $canonical ) {
    global $post;

    $paged = get_query_var( 'paged' );

    if ( isset( $paged ) && (int) $paged > 0 ) {
        return trailingslashit( trailingslashit( $canonical ) . 'page/' . $paged );

        return $url;
    }

    return $canonical;
}

add_filter( 'wpseo_opengraph_url', 'gb_wpseo_canonical' );

The result is a matching og:url and a canonical tag:

<link rel="canonical" href="https://www.example.com/category/news/page/2/">
<link rel="prev" href="https://www.example.com/category/news/">
<link rel="next" href="https://www.example.com/category/news/page/3/">
<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="News Archives - Page 2 of 4 - My Awesome Website">
<meta property="og:description" content="See the latest news from My Awesome Website about all these awesome things.">
<meta property="og:url" content="https://www.example.com/category/news/page/2/">

Related posts