Configuring a custom canonical URL in Yoast Wordpress SEO Plugin

Sent due to lack of responses.

I'm having trouble setting up a custom canonical name using the Wordpress SEO API: http://yoast.com/wordpress-seo-api-docs/

I have a custom post type called a design that uses custom URL rewriting. He takes the base page / design / and adds the name of the design to it, for example / design / a -design /. Canonical in Wordpress SEO is / design / page by default.

I want to write a function that determines if it is a design page and returns another canonical one. I can check if it was a design page by doing if ($design == ""){ and I tried to use a custom link URL, but the function just completely removes the canonical version.

Here is my main 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' ) 

It is obvious that something is wrong, but I'm not quite sure what.

Thoughts?

+6
source share
2 answers

You can 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' ); 
+10
source

Hi, I couldn’t reply to the above message, so I’m just doing another one.

I tried using the answer from stealthyninja for a similar problem, and it almost worked. Except for the last part: an empty else statement. It does not display the result if the rule does not match.

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

The following snippet code 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' ); 
+6
source

Source: https://habr.com/ru/post/925754/


All Articles