I’d like to intercept 404 errors and do some things before to show the 404 error page.
How can intercept the 404 error?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
As was mentioned in a comment, template_redirect would be an appropriate hook for intercepting a 404 before the template is loaded.
function wpd_do_stuff_on_404(){
if( is_404() ){
// do stuff
}
}
add_action( 'template_redirect', 'wpd_do_stuff_on_404' );
Refer to the Action Reference for the general order of actions on the front end. The main query runs between the posts_selection and wp actions, so that is the earliest you can determine that a request is a 404. The template is then loaded after template_redirect, so it’s too late to set headers after that point.
Method 2
Using below code you can directly redirect on home page when 404 call, please remove all code from the 404.php file and add below code.
<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: ".get_bloginfo('url'));
exit();
?>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0