How do I redirect all 404 errors of a specific post type to another URL?

I have a custom post type containing job listings, that is highly volatile. Jobs are frequently added and removed. Our analytics show that a lot of crawling errors are for detail pages of jobs that have been unlisted.

The solution I came up with is to redirect all visits for non-existant URLs within the CPT’s slug to the job listing overview, and I would like to automate this.

How would I go about this? I’m looking for a solution that does this very early and skips as much unnecessary calls as possible. (i.e. something earlier than doing this in header.php, ideally as an action)

Example:

  • mydomain.com/jobs/existingjob/ delivers the detail page for the job
  • mydomain.com/jobs/nojobhere/ does not exist and would throw a 404 but instead gets redirected to
    mydomain.com/jobs/

3 Answers
3

It looks like template_redirect is as far up the WordPress action chain you can go while still being able to detect that a 404 error is being thrown. This action will trigger before any template files would be loaded so it will happen before loading unnecessary resources.

You can try adding this into your /wp-content/themes/yourtheme/functions.php file to achieve a dynamic redirect for all 404’s that happen when viewing single jobs:

add_action( 'template_redirect', 'unlisted_jobs_redirect' );
function unlisted_jobs_redirect()
{
    // check if is a 404 error, and it's on your jobs custom post type
    if( is_404() && is_singular('your-job-custom-post-type') )
    {
        // then redirect to yourdomain.com/jobs/
        wp_redirect( home_url( '/jobs/' ) );
        exit();
    }
}

Leave a Comment