Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a custom canonical URL in Yoast Wordpress SEO Plugin

Tags:

php

seo

wordpress

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?

like image 725
Ian Avatar asked Sep 19 '12 10:09

Ian


1 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' );
like image 167
stealthyninja Avatar answered Sep 30 '22 14:09

stealthyninja