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.
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.exit;
ordie;
otherwise the code continues as usual.die;
helped me understand that the code was run inside the 404 page content, not before. I switched the hook totemplate_redirect
and addeddie;
after the redirect - now google understands it.