Add WPML Language Links to a Menu Location
Appends links to the other WPML languages of the current page at the end of a chosen theme menu, labelled with each language's native name.
Opens WPIDE on
Code
$wpide_location = 'primary'; // Theme menu location.
add_filter( 'wp_nav_menu_items', function ( $items, $args ) use ( $wpide_location ) {
if ( ! defined( 'ICL_SITEPRESS_VERSION' ) || empty( $args->theme_location ) || $args->theme_location !== $wpide_location ) {
return $items;
}
$languages = apply_filters( 'wpml_active_languages', null, array( 'skip_missing' => 1 ) );
if ( empty( $languages ) || ! is_array( $languages ) ) {
return $items;
}
foreach ( $languages as $lang ) {
if ( ! empty( $lang['active'] ) ) {
continue;
}
$items .= sprintf(
'<li class="menu-item menu-item-language menu-item-language-%1$s"><a href="%2$s" hreflang="%3$s" lang="%3$s">%4$s</a></li>',
esc_attr( $lang['language_code'] ),
esc_url( $lang['url'] ),
esc_attr( $lang['tag'] ?? $lang['language_code'] ),
esc_html( $lang['native_name'] )
);
}
return $items;
}, 10, 2 );
Notes
Set $wpide_location to your theme's menu location (see Appearance > Menus > Manage Locations). Languages without a translation of the page are skipped.
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.