Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * the below code goes into functions.php of the current theme
- * The first function registers WP nav menus for each locale on your site
- * It's possible to get the locales with the function get_available_languages()
- * or pass them manually as an array
- */
- add_action( 'init', 'custom_register_nav_menus' );
- function custom_register_nav_menus() {
- // get all languages in theme's languages folder (.mo files)
- // $available_locales = get_available_languages( STYLESHEETPATH . '/languages' );
- // or manually set available locales
- $available_locales = array ( 'en', 'zh' ) ;
- // register a nav menu for each of the locales
- foreach ( $available_locales as $locale ) {
- // the theme locations would be called "primary-en" and "primary-zh"
- register_nav_menu( "primary-{$locale}", "Main Menu ({$locale})" );
- }
- }
- /**
- * The below functions changes the WP's active locale based on the request uri
- * You must have pretty permalink enabled for this to work and the pages for
- * each language need to be under a master page with the slug of 'en' or 'zh'
- */
- add_filter( 'locale', 'swpl_change_locale' );
- function swpl_change_locale( $locale ) {
- global $swpl_customized_locale;
- // If we've already done this, return the value we previously found
- if ( ! empty( $swpl_customized_locale ) )
- return $swpl_customized_locale;
- // get all languages in theme's languages folder (.mo files)
- // $available_locales = get_available_languages( STYLESHEETPATH . '/languages' );
- // or manually set available locales
- $available_locales = array ( 'en', 'zh' ) ;
- // loop 'em
- foreach ( $available_locales as $lang ) {
- // if using get_available_languages(), the returned locale would be in the format 'en_US'; use this to convert it to 2-letter locale
- // $short_locale = strtolower ( substr( $lang, 0, 2 ) );
- // if request uri starts with one of the locales
- if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/' . $short_locale ) === 0) {
- // assign locale
- $locale = $swpl_customized_locale = $lang;
- break;
- }
- }
- return $locale;
- }
- /**
- * Then call your menu like this in your template
- */
- wp_nav_menu( array(
- 'theme_location' => 'primary-' . get_locale(),
- )
- );
Advertisement
Add Comment
Please, Sign In to add comment