Quantcast
Channel: BIOSTALL » PHP
Viewing all articles
Browse latest Browse all 57

Prevent WordPress Redirecting to Nearest Matching URL

$
0
0

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:

http://mysite.com/contact-us

But the user types in:

http://mysite.com/contact

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.


Viewing all articles
Browse latest Browse all 57