I’d like to intercept 404 errors and do some things before to show the 404 error page.
How can intercept the 404 error?
I’d like to intercept 404 errors and do some things before to show the 404 error page.
How can intercept the 404 error?
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.