Skip to content

Instantly share code, notes, and snippets.

@isotrope
Last active March 22, 2022 06:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isotrope/8ac9fae6c57d93d73f33 to your computer and use it in GitHub Desktop.
Save isotrope/8ac9fae6c57d93d73f33 to your computer and use it in GitHub Desktop.
Add (a) Polylang switcher menu item(s) to any menu.
/*
Example CSS of how I was showing one OR the other, based on brwoser-width
*/
@media (max-width: @grid-float-breakpoint-max) {
.language-code {
display: none;
}
}
@media (min-width: @grid-float-breakpoint) {
.language-full-name {
display: none;
}
}
<?php
/**
* Automatically adds a Polylang Language switcher to a menu
*
* ! Please note that this will actually show the language in shortened form ('En')
* ! as well as long form ('English')
*
* You can choose to show / hide each span with CSS
*
* .language-code is the short-form
* .language-full-name is the long-form
*
* In my case, I wanted to show 'En' on desktop sizes and 'English' for my fly-out mobile menu.
*
*/
/**
* This hook lets you add html to the end of a menu list (before the closing '</ul>'
*
* Reference: https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/
*/
add_filter( 'wp_nav_menu_items', 'iso_add_menu_lang_switcher', 10, 2 );
function iso_add_menu_lang_switcher( $items, $args ) {
/**
* Enter the name of the menu slug you want to add this switcher to
*
* Chances are that if you look in your theme's function.php or elsewhere in the code,
* you'll find a register_nav_menus function.
* If you look at the arguments, you should find the slug for menu you want to affect
*/
$menu_slug = 'primary';
/**
* Personally, I see no reason to show the current language (For example, "French" if you're on a French page)
* If you really want to show it, set this to true;
*/
$show_current_language = false;
if ( $menu_slug === $args->theme_location ) {
$langs = array();
if ( function_exists( 'icl_get_languages' ) ) {
$available_languages = icl_get_languages( 'skip_missing=0' );
foreach ( $available_languages as $l ) {
if ( ! $l['active'] || $show_current_language ) {
//$langs[] = '<a href="' . $l['url'] . '" class="language_switch_link"><span class="language-code">' . $l['language_code'] . '</span><span class="language-full-name">' . $l['native_name'] . '</span></a>';
/**
* Broken into multiple lines to make easier to read / alter
*/
$menu_item = '<li class="menu-item language-switcher">';
$menu_item .= '<a href="' . $l['url'] . '" class="language_switch_link">';
$menu_item .= '<span class="language-code">' . $l['language_code'] . '</span>';
$menu_item .= '<span class="language-full-name">' . $l['native_name'] . '</span>';
$menu_item .= '</a>';
$menu_item .= '</li>';
$langs[] = $menu_item;
}
}
$items .= join( '', $langs );
}
}
return $items;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment