Here’s what I’ve come up with:
if(is_single()){
$reqURI = explode('/',$_SERVER['REQUEST_URI']); // explode url into an array
//if last part of url is a number, then redirect.
if(is_numeric($reqURI[count($reqURI) - 2])){
header ('HTTP/1.1 301 Moved Permanently');
header('Location: ' . get_permalink($post->ID));
exit;
}
}
What this is doing is getting the last bit of the URL (the last section between forward slashes) and seeing if it is a number or not. If it is not a number then it does not do anything else (ie, the page loads as normal), but if it is a number then it queries WordPress for the permalink of the post that you’re trying to view (using the number that was evaluated) and then redirects to the permalink address, also returning a 301 at the originally requested shortened address.
For example, if I try to go to:
/514/
the above script will recognize that the address ends in a number, it will use that number to get the permalink, and it will redirect to:
/514/this-is-the-post-title/
It also works if I just type:
/514
First WordPress automatically redirects to:
/514/
and then my script takes over from there and does it’s thing.
A couple of things to note:
1) The above script must be placed in your code before any html (or anything that might interpreted as part of the final page, such as carriage returns outside of PHP tags). Otherwise you’ll get an error that it can’t send/change headers because they’ve already been sent/changed. You’ll probably have to experiement to find how high in your code it has to be to work, but if you can just put it at the very top of your PHP it should work.
2) I have no idea what problems my method might indirectly cause. I’ve tried to make it efficient (e.g., evaluating the url to decide whether or not it even needs to query WordPress for the permalink), but I am admittedly still quite new at PHP and WordPress especially. So, I don’t know if or how well this method will scale.
3) My site is set up as
https://www.example.org/blog
It is possible that if you have WordPress installed at https://www.example.org (without the /blog) that you might need to change the 2 to something else, although I don’t think you should need to. The 2 was what I needed to subtract to get the last bit of the url.
I would LOVE to get some feedback on this code. What problems do others see that I’m missing? How could things be done better? How could I have come up with something so brilliant (ha ha! I’m joking here, though I’ll certainly accept compliments.)? ??
Seriously though, I’d love to get some input/feedback from more experienced coders.
??