How to fix incorrect AIOSEO canonical URLs in a subdirectory WP

Here's how to fix the issue where the canonical URL output by All in One SEO is duplicated on a WordPress site installed in a subdirectory.
Specifically
On a WordPress site installed under /blog/
The canonical tag sometimes looked like this:
<link rel="canonical" href="https://example.com/blog/blog/">
Subpages looked like this:
<link rel="canonical" href="https://example.com/blog/blog/?p=00000">
There was no such item in the AIOSEO settings screen,
and changing these settings seemed like it would resolve it, but

Conclusion
We will use a filter hook.
Add this to functions.php.
//AIOSEO Canonical URL Normalization Filter Hook
add_filter( 'aioseo_canonical_url', 'aioseo_filter_canonical_url');
function aioseo_filter_canonical_url($url){
if(strpos($url, '/blog/blog/')){ //'/blog/blog/'が含まれる時
$result = str_replace('/blog/blog/', '/blog/', $url); //'/blog/'に置き換える
return $result;
}else{
return $url;
}
}
Using the aioseo_canonical_url filter hook,
when the string "/blog/blog/" is present, it is replaced with "/blog/".
The official documentation is here:




If this was helpful, we appreciate your support!
All support received will be used for childcare.
Or support us by buying something from the buttons below
(You don't have to buy the linked product.)
Amazon
楽天市場
Yahoo!ショッピング
PR