Here is a trick, redirections in WP are complex. You can get 3 situations when they can happen.
- There is matched to your url rule, but no posts returned on wp_query from generated
query_string
. - There is no rule that match your
404
. - Other Situations ( you wouldn’t run into this on your own, so don’t worry. )
Based on thi, 404 redirection can be triggered on 3 wp points.
request
wp_headers
template_redirect
So you can use this as template for your redirection logic
add_filter( 'request', function( Wp_Query $wp_query ){
if ( isset( $wp_query['error'] ) && 404 === intval( $wp_query['error'] ) ){
// redirection logickgoes here...
}
return $wp_query;
});
add_filter( 'wp_headers', function( $headers, $wp ){
if ( isset( $wp->query_vars['error'] ) && 404 === intval( $wp->query_vars['error'] ) ) {
// redirection logic goes here...
}
return $headers;
}, 10, 2);
add_action( 'template_redirect', function( $params ){
if ( is_404() ) {
// redirection logic goes here.
}
});
These are a bit hacky ways to do redirection on 404 error, but this is what I come up when run into sites migration myself.