We use WordPress and would like to link amp to amp if the linked page has an amp version. We have amp structured like that: test.de/test/amp
Unfortunately this code in my functions.php isnt applying to links hard-coded inside of the post content. What do I have to change, so its working for every internal link:
add_filter( 'post_link', function( $url, $post ) {
static $recursing = false;
if ( $recursing ) {
return $url;
}
$recursing = true;
if ( ! function_exists( 'post_supports_amp' ) || ! post_supports_amp( $post ) ) {
return $url;
}
if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) {
$url = amp_get_permalink( $post->ID );
}
$recursing = false;
return $url;
}, 10, 2 );
At the moment its also applying to the canonical link, which is really bad for seo. How to prevent this?
3
Answers
If you want to replace hardcoded links inside of your post content I would suggest you use the “the_content” filter for wordpress.
https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content
From this you should be able to regular expression match the link and append /amp to it.
Pseudo code example:
Add these functions to your theme’s ‘functions.php’.
The first function will provide the AMP URL if exists.
The second one will loop through each URL in the content and change to AMP URL if valid.
The last one will rewrite the canonical URL that displayed via Yoast SEO plugin.
I have tested the code submitted by Outsource WordPress, and in general it works fine but the ‘amp_override_canonical function overwrites all the urls of the page removing the /amp.
I have made some changes to this piece of code but they do not work as I expect. It seems that the ‘wpseo_canonical’ function is being invoked in a different context.