I am in the process of making a new WordPress website, starting from an existing WordPress which has a really long history, with a lot of plugins.
The problem I encountered was that the old website had pages that ended with “.htm”. Why would someone bother to have urls that ended with “.htm” extension is way beyond me, but considering that the client wanted to keep those urls the same (“for the moment”), and I didn’t want to add another plugin, I had to find a way to deal with those urls.
So, I started by allowing the extension in the rewrite rules of the new WordPress instance:
function avenirer_custom_rewrites() {
add_rewrite_rule("^(.*)\.htm?", 'index.php?page_id=$matches[1]', 'top');
}
add_action('init', 'avenirer_custom_rewrites');
After that, we see that the url is accepted, but a redirect is done with 301 code. But we do not want a redirect, as this would not solve our problem. For this we need to remove the redirection filter:
function avenirer_no_redirect_extension($query) {
if(strpos($query->request, '.htm') !== false) {
remove_filter('template_redirect','redirect_canonical');
}
}
add_filter('parse_request', 'avenirer_no_redirect_extension', 10, 1);
Hope this helps anyone. Spent a day looking for a solution. If you have a better one, please be kind and share.