3

I'm using a snippet to overwrite the canonical URL in YoastSEO for WordPress/WooCommerce. The snippet is based on the official docs example: https://developer.yoast.com/features/seo-tags/canonical-urls/api/

Here's my code:

function prefix_filter_canonical_example( $canonical ) {
 
    if (is_shop() && is_paged() ) :
 
        $canonical = get_permalink(woocommerce_get_page_id( 'shop' )).'page/'.get_query_var('paged').'/';
    
    elseif(WCV_Vendors::is_vendor_page()):
    
        $vendor_shop = urldecode( get_query_var( 'vendor_shop' ) );
        $vendor_id   = WCV_Vendors::get_vendor_id( $vendor_shop );
        $canonical  = WCV_Vendors::get_vendor_shop_page( $vendor_id );
    
    endif;
    
    return $canonical;
    
}   
add_filter( 'wpseo_canonical', 'prefix_filter_canonical_example' );

The code doesn't do anything to the canonical URL regardless of the content I return. But the if/else works fine and if I echo the content of $canonical I see the correct URLs.

I tried it already with the basic storefront theme and I deactivated nearly all plugins. But the snippet won't work. Is there anything I miss?

Cray
  • 5,307
  • 11
  • 70
  • 166
  • 3
    As i can see default priority of yoast filter is 10 and in your add_filter() you didn't pass anything and wordpress executed function in the order in which they were added to the action so may be adding priority to 20 will do job for you – Gautam Golakiya Mar 11 '21 at 12:47
  • 1
    That's it! I tried it with 10 but it works with 20 now! Can you add this as answer? – Cray Mar 11 '21 at 12:55
  • 1
    I saw your recommendation for the SEO Framework plugin on your profile weeks ago. I plan to change the plugin but it may be a bigger task... So I need to work with Yoast for now :( – Cray Mar 11 '21 at 13:01

1 Answers1

6

If you don't pass any priority to the action wordpress will take it as 10. Yoast SEO also call this filter to add canonical url so wordpress executed function in the order in which they were added to the action.

So change this line

add_filter( 'wpseo_canonical', 'prefix_filter_canonical_example' );

With this

add_filter( 'wpseo_canonical', 'prefix_filter_canonical_example', 20 );
Gautam Golakiya
  • 453
  • 2
  • 12