Home » Php » php – Setting a custom canonical URL in Yoast WordPress SEO Plugin

php – Setting a custom canonical URL in Yoast WordPress SEO Plugin

Posted by: admin July 12, 2020 Leave a comment

Questions:

Reposted due to no replies.

I’m having some trouble setting a custom canonical title using the WordPress SEO API: http://yoast.com/wordpress-seo-api-docs/

I have a custom post type called designs which uses a custom URL rewrite. It takes the base page /design/ and adds the design name to it like /design/a-design/. The canonical in WordPress SEO by default is the /design/ page.

What I want to do is write a function which determines if it is a design page and return a different canonical. I can test whether it’s a design page by doing if ($design == ""){ and I tried to use the custom permalink URL, but the function just removes the canonical completely.

Here’s my basic function:

function design_canonical(){
    if ($design == "") {    
        // Leave blank and Yoast SEO will use default canonical for posts/pages
    }
    else {
        return $design['detailslink'];
    }
}
add_filter( 'wpseo_canonical', 'design_canonical' )

Quite clearly doing something wrong, but I’m not entirely sure what.

Thoughts?

How to&Answers:

You could try something like:

function design_canonical($url) {
    global $post;

    if ( get_post_type( $post->ID ) == 'design' ) {
        return site_url( '/design/' . $post->post_name );
    } else {
        // Do nothing and Yoast SEO will use default canonical for posts/pages
        return $url;
    }
}
add_filter( 'wpseo_canonical', 'design_canonical' );

Answer:

Hi i couldn’t answer to the above post so I just make another one.

I tried to use the answer from stealthyninja for a similar problem and it almost worked. Except the last part: the empty else statement. It renders no output if the rule doesn’t match.

Maybe Yoast updated his plugin on this within the last 2 years so I thought I should mention it here.

The following Code-Snippet solved my problem:

function design_canonical($url) {
    global $post;

    if ( get_post_type( $post->ID ) == 'design' ) {
         return site_url( '/design/' . $post->post_name );
    } else {
         return $url;
    }
}
add_filter( 'wpseo_canonical', 'design_canonical' );