Send Secondary-Language 404s to That Language's Homepage
When a visitor hits a missing page in a non-default WPML language, sends them to the homepage of that language instead of a 404, keeping them in their language.
Opens WPIDE on
Code
add_action( 'template_redirect', function () {
if ( ! is_404() || ! defined( 'ICL_SITEPRESS_VERSION' ) ) {
return;
}
$current = apply_filters( 'wpml_current_language', null );
$default = apply_filters( 'wpml_default_language', null );
if ( ! $current || $current === $default || 'all' === $current ) {
return;
}
wp_safe_redirect( apply_filters( 'wpml_home_url', home_url( '/' ) ), 302 );
exit;
} );
Notes
Uses a 302 redirect so search engines keep reporting real broken links; change to 301 if you prefer. The default language keeps its normal 404 page.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.