1

I have made a function on a wordpress site.

The functions purpose is the following.

1) if the post is not found, redirect to the archive of the post.

Should be fairly easy right?

Well - according to all sorts of tools, it isn't.

I start by creating this function:

function check_database_for_existance() {
    if (is_main_query() && is_404() && !is_archive()){
        //Do all sorts of magic here to find the correct link.

        $redirectLink = "found-by-wp_magical-conditions";

        header("HTTP/1.1 301 Moved Permanently"); //Or temporery, doesn't matter - doesn't work
        header("Location: ".$redirectLink);
    }
}

add_action('pre_get_posts', 'check_database_for_existance'); 

Now.. All tools I have for testing, suggest that it basically works wonderfully, everything from Toolbot to playstation3 understand the redirects fine.

But Googlebot (and other searchbots) refuses to accept it, and still sees the 404 page.

I have to use the pre_get_post hook - since i need to find out, if the posts exist, right?

Is there any way of forcing google to follow the redirect?

Am I redirecting to late in the process?

The documentation on Googlebots results are not very well documented IMO.

I have tested on : http://www.redirect-checker.org/index.php and using the ScreamingFrog program

I am at the ropes here - simply can not understand, why google won't follow the redirects.

  • Have you tested your redirecting URL with curl on the command line? I test with curl --head http://example.com/page which shows exactly what the header is. If you are redirecting too late in the process it would show a 404 first and the your 301 later. – Stephen Ostermiller Oct 2 '18 at 10:41
  • After your header calls try adding exit; or die; otherwise the code continues as usual. – Dave Oct 2 '18 at 14:47
  • @Dave - you are beautiful - the die; helped me understand that the code was run inside the 404 page content, not before. I switched the hook to template_redirect and added die; after the redirect - now google understands it. – Stender Oct 4 '18 at 7:18
  • If you want the points, you can answer - I do believe that this will be helpfull for future people with similar problems. – Stender Oct 4 '18 at 9:13
1

After your header calls you need to exit or die. If you don't the script continues on as usual which likely explains why you are seeing the results you are.

function check_database_for_existance() {
    if (is_main_query() && is_404() && !is_archive()){
        //Do all sorts of magic here to find the correct link.
        $redirectLink = "found-by-wp_magical-conditions";
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: ".$redirectLink);
        die;  // we are done here, nothing more to do
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.