Polylang Language Switcher Shortcode
Adds a [wpide_pll_switcher] shortcode that prints an accessible Polylang language list or dropdown anywhere, with flags, names or both.
Opens WPIDE on
Code
add_shortcode( 'wpide_pll_switcher', function ( $atts ) {
if ( ! function_exists( 'pll_the_languages' ) ) {
return '';
}
$atts = shortcode_atts( array(
'dropdown' => '0',
'flags' => '0',
'names' => '1',
'hide_current' => '0',
'hide_untranslated' => '0',
), $atts, 'wpide_pll_switcher' );
$languages = pll_the_languages( array( 'raw' => 1, 'hide_if_empty' => 0 ) );
if ( empty( $languages ) || ! is_array( $languages ) ) {
return '';
}
$languages = array_filter( $languages, function ( $lang ) use ( $atts ) {
if ( $atts['hide_current'] && ! empty( $lang['current_lang'] ) ) {
return false;
}
return ! ( $atts['hide_untranslated'] && ! empty( $lang['no_translation'] ) && empty( $lang['current_lang'] ) );
} );
if ( $atts['dropdown'] ) {
$id = wp_unique_id( 'wpide-pll-ls-' );
$html = '<label class="screen-reader-text" for="' . esc_attr( $id ) . '">' . esc_html__( 'Language' ) . '</label><select id="' . esc_attr( $id ) . '" class="wpide-pll-switcher" onchange="if(this.value){window.location.href=this.value;}">';
foreach ( $languages as $lang ) {
$html .= sprintf( '<option value="%1$s" lang="%2$s"%3$s>%4$s</option>', esc_url( $lang['url'] ), esc_attr( $lang['locale'] ), selected( ! empty( $lang['current_lang'] ), true, false ), esc_html( $lang['name'] ) );
}
return $html . '</select>';
}
$html = '<nav class="wpide-pll-switcher" aria-label="' . esc_attr__( 'Language' ) . '"><ul style="list-style:none;margin:0;padding:0;display:flex;flex-wrap:wrap;gap:.75em">';
foreach ( $languages as $lang ) {
$inner = '';
if ( $atts['flags'] && ! empty( $lang['flag'] ) ) {
$inner .= wp_kses( $lang['flag'], array( 'img' => array( 'src' => true, 'alt' => true, 'width' => true, 'height' => true, 'style' => true ) ) ) . ' ';
}
if ( $atts['names'] || ! $atts['flags'] ) {
$inner .= esc_html( $lang['name'] );
} else {
$inner .= '<span class="screen-reader-text">' . esc_html( $lang['name'] ) . '</span>';
}
$html .= sprintf(
'<li><a href="%1$s" hreflang="%2$s" lang="%2$s"%3$s>%4$s</a></li>',
esc_url( $lang['url'] ),
esc_attr( $lang['locale'] ),
! empty( $lang['current_lang'] ) ? ' aria-current="true" style="font-weight:700"' : '',
$inner
);
}
return $html . '</ul></nav>';
} );
Notes
Attributes: dropdown="1", flags="1", names="1", hide_current="1", hide_untranslated="1" (skip languages without a translation of this page).
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.