Is there a way for the menu to be translated when I choose the website language? Does anyone have a solution to do it without using the plugin?
-
I recently wrote code which switched between two different menus depending on the language the user was browsing in. It wasn't that easy! A plugin might help, but I couldn't recommend one from experience. I know WPML is popular, might do what you need... – Dan Jan 15 '15 at 9:46
You can create a menu use another language. Then you use conditional code to switch the menu. or you can use title attribute of menu.
if($language=='us'):
wp_nav_menu(menu1);
else:
wp_nav_menu(menu2);
endif;
you could use Polylang plugin which will create different template for each language, and integrate different menu for each language.
start reading here and dig in: https://wordpress.org/plugins/polylang/
I just wrote a simple hook to use the normal translation functions, which I just added into my theme's functions.php
file.
/** Translate menu items. */
function translate_menu_item_frontend($item_output, $item) {
if (property_exists($item, 'title')) {
$parts = explode('|', $item->title);
$context = count($parts) > 1 ? $parts[0] : null;
$text = end($parts);
return preg_replace(
'/(<.*?>).*(<\/.*?>)/s', '$1' . _x($text, $context) . '$2', $item_output, 1);
}
return $item_output;
}
add_filter('walker_nav_menu_start_el', 'translate_menu_item_frontend', 20, 2);
add_filter('megamenu_walker_nav_menu_start_el', 'translate_menu_item_frontend', 20, 2);
This means you can, for example, set a menu item navigation label to 'Home' and it will be translated with the builtin core translations. You can also specify a context separated with |
, so for example 'Theme starter content|Contact' would use the builtin core translations for the word 'Contact'.
This can easily be adapted to support custom domains if you want to provide your own translations too.
-
On a related note, if you want the site to automatically change language based on the user's browser settings, I wrote a small plugin for that here: wordpress.org/plugins/preferred-locale – Sam Bull Nov 26 '17 at 1:35