I have an old website that I’m revamping with a custom new WordPress theme. The old site had a custom (non-WP based) downloads archive that mapped URLs like this:
/downloads/view.php?id=2
The ID maps to a download item in a separate MySQL database.
I’d like to move everything over to WordPress in this refresh and I’m going to be using a custom post type to handle the downloads section, with a custom field that maps the “old ID” to the new post. This isn’t difficult and I know how to do this, but the issue becomes remapping the old URLs to the new locations.
The issue I see is that the older URLs are all PHP files (have an extension of .php
). How would I go about create a plugin or WordPress function in my theme’s functions.php file to redirect these old URLs to a new URL. Essentially, I just need to have a WordPress function redirect from /downloads/view.php?id=2
to /downloads/2/
, or another more optimized URL (/downloads/title-of-archive
).
How would I go about handling pages with a URL of “/downloads/view.php
” and “/downloads/download.php
” and performing the redirect?
I know I can use the .htaccess
file, but I’d prefer to do this directly in a WordPress plugin if possible for portability…
I ended up solving the issue by hooking onto the “
template_redirect
” action. After that, I check if the pageis_404()
and then check if the URL matches my pattern. I set the appropriate header (301
versus the404
that normally would be triggered) and perform my redirect. My code is below.You could do this with rewrites, but honestly, it’s not a rewrite what you want. A rewrite would just have the old url to act like the new url instead of redirecting it to the new location. Please not that you still need to make sure
/downloads/id/
is handled by your WordPress. Now there you could use rewrite.Add the following code to your templates
function.php
:To redirect
/downloads/view.php?id={some-name}
to/downloads/{some-name}/
, add the following to your .htaccess file, before the default WordPress rulesIt will also let search engines know that your downloads have moved, and to update their index.
Old Custom Php URLS Redirect to Home or other pages .htaccess code