Stopping WordPress From Redirecting Matched Slugs

July 1, 2014 Development, PHP, WordPress

Stopping WordPress From Redirecting Matched Slugs

A friend of mine asked recently why an old link was redirecting to a similarly named page in WordPress. Even though the page had been deleted, the link was still active and going to another page.

I thought it was due to WordPress automatically redirecting pages that are renamed to prevent broken links. After some digging, it turns out that the WordPress core uses canonical URLs to redirect slugs that are close matches.

It all starts with the redirect_canonical() filter. The description for this filter says “Will also attempt to find the correct link when a user enters a URL that does not exist based on exact WordPress query. Will instead try to parse the URL or query in an attempt to figure the correct page to go to.”

In this filter, a function named redirect_guess_404_permalink() is called on line 96.

$redirect_url = redirect_guess_404_permalink();

Thanks to Jan Fabry at Stack Exchange for the following code that can be added to your theme’s function.php file to stop this WordPress default behaviour.

add_filter('redirect_canonical', 'no_redirect_on_404');
function no_redirect_on_404($redirect_url)
        return false;
    return $redirect_url;

The code is so simple and elegant that I wish it would be included in the next WordPress update as a yes/no option. Fabry’s hook onto the redirect_canonical() filter just returns false if the page is not found, stopping the script right then and there. The guess function is not used and the visitor is redirected to the 404 error page.

I understand why WordPress does this – to prevent 404 results, allow for human error, be more acceptable to mistakes – and usually I would gladly welcome this feature, but sometimes I’d like a broken link to be a broken link. While it doesn’t hurt SEO value and does allow for multiple ways to access the same page, it can be confusing when a redirect is taking place that you haven’t setup and one that you can’t remove.

Let's Talk About Your New Website

View Portfolio Contact Today