Create a custom language switcher

We offer a widget and the “quick links” to show links to translations, but many users need a custom solution at other places or in a formatting we just don’t give them (yet).

There is a handy helper function to get all the links as an array: mlp_get_interlinked_permalinks(). It returns an array with the text (human readable language name), the permalink to the other site’s translation and an entry lang (the language code) – for each single translation.

You can use that to create your own language switcher. The following function creates a string that might look like this:

EN | DE | RU

Add it to your theme’s functions.php.

/**
 * Create a navigation between translations
 *
 * @param  string $between  Separator between items
 * @param  string $before   HTML before items
 * @param  string $after    HTML after items
 * @return string
 */
function mlp_navigation(
    $between = ' | ',
    $before  = '<p class="mlp-lang-nav">',
    $after   = '</p>'
)
{
    $links = (array) mlp_get_interlinked_permalinks();

    if ( empty ( $links ) )
        return '';

    $items = array ();

    foreach ( $links as $link ) {
        if ( isset ( $link['text'] ) ) {
            $text = $link['text'];
        }
        else {
            // take just the main code
            $first = strtok( $link['lang'], '_' );
            $text  = mb_strtoupper( $first );
        }

        $items[] = sprintf(
            '<a href="%1$s" hreflang="%2$s" rel="alternate">%3$s</a>',
            esc_url( $link['permalink'] ),
            esc_attr( $link['lang'] ),
            $text
        );
    }

    return $before . join( $between, $items ) . $after;
}

Now you can call the function wherever you need it without any arguments:

echo mlp_navigation();

Don’t forget the closing semicolon!

If you want to get a list, you can change the parameters:

echo mlp_navigation(
    '</li><li>', // between items
    '<ul class="mlp-lang-nav"><li>', // before
    '</li></ul>' // after
);

We will add support for custom menus in one of the next versions of Multilingual Press, so you can create your own menus with drag and drop.