Change cannonical URL after changing url with add_rewrite_rule()
So, I'm making a plugin for some niche application for my customer which involves a table with data, and I created a page within the plugin to show more in-depth information about the table row.
This is how I'm making the rewrite:
function mytableplugin_page_rewrite(){
$page_slug = 'mytablepluginpage';
// urls will be in the form
// /your-page/42/
add_rewrite_rule(
'mytableplugin/([0-9a-zA-Z_-]+)/?$',
'index.php?pagename=' . $page_slug . 'tid=$matches[1]',
'top'
);
}
But the redirect doesn't affect the canonical URL, so every mytableplugin
page has the same mytablepluginpage
canonical URL
I'm not using Yoast SEO plugin, and I don't want my plugin to depend on it, so, how can I change the canonical link of the page? I want the custom name (mytableplugin != mytablepluginpage)
to be kept and the argument to keep on the canonical URL
It's being a problem because the TranslatePress plugin is using the wrong URL when switching languages, it's throwing me back into the mytablepluginpage
page that has no content without the queries.
Edit: I tried some more stuff, and hijacking the rel_canonical function does work to change the canonical URL, but doesn't solve the problem of the translatepress plugin having the wrong URL for the language switching, here's the code I used:
remove_action('wp_head', 'rel_canonical');
add_action('wp_head', 'my_rel_canonical');
function my_rel_canonical() {
if (is_page('mytablepluginpage')) {
global $wp;
echo link rel='canonical' href='.home_url( $wp-request ).'/\n;
} else {
rel_canonical();
}
}
(This last code came from this StackOverflow question)
Thanks in advance!
Topic rel-canonical url-rewriting plugin-development Wordpress
Category Web