Prevent WordPress Redirecting to Nearest Matching URL

July 4th, 2014 - Posted by Steve Marks to PHP, Web Development.

WordPress comes with a nifty feature which enables it to navigate to the closest matching URL if the one typed in doesn’t exist. This reduces the chance of a user getting presented with a 404 page if they’ve slightly mistyped a page’s URL.

An example of this would be; imagine we have a page with the following URL:

But the user types in:

In this scenario it would redirect the user to the closest matching page.

It’s a pretty cool feature and one I use myself on my own site if I can’t quite remember the full URL to a page. I can just type in the first part of the URL and WordPress will redirect me accordingly if it finds a match.

Turning It Off

Yes, the above is great, but what if we want to disable it? On a site recently I needed to do exactly this when I was using URL’s that didn’t relate to pages and, instead, jumped to different parts of a single page site.

The solution was to add the below code to my theme’s functions.php file:

remove_filter('template_redirect', 'redirect_canonical');

Once the above code had been added, WordPress no longer tried to send me to the page with the closest URL. This is probably a very rare scenario but it’s good to know that this can be disabled with a single line of code.

Tags: ,
This entry was posted on Friday, July 4th, 2014 at 9:08 am by +Steve Marks and is filed under PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first