I ended up solving the issue by hooking onto the “template_redirect
” action. After that, I check if the page is_404()
and then check if the URL matches my pattern. I set the appropriate header (301
versus the 404
that normally would be triggered) and perform my redirect. My code is below.
add_action('template_redirect', 'handle_download_urls');
function handle_download_urls(){
if(is_404()){
if(preg_match('/\/downloads\/(?:view\.php|download\.php)/', $_SERVER['REQUEST_URI']) && isset($_GET['id'])){
// Do lookup of post based on custom metadata field
// Redirect and change header
status_header(301);
header('Location: [URL]');
}
}
}