LC
php
Back to Snippets

WordPress Polylang Language Switcher Shortcode

Create a custom language switcher shortcode with flags for Polylang.

wordpresspolylangi18nshortcode
php
      function polylang_switcher_shortcode() {
    $output = '<ul class="lang-switcher">';
    $languages = pll_the_languages(array(
        'raw' => 1,
        'show_flags' => 1,
    ));

    foreach ($languages as $lang) {
        $active = $lang['current_lang'] ? ' class="active"' : '';
        $output .= '<li' . $active . '>';
        $output .= '<a href="' . esc_url($lang['url']) . '">';
        $output .= $lang['flag'] . ' ' . esc_html($lang['name']);
        $output .= '</a></li>';
    }

    $output .= '</ul>';
    return $output;
}
add_shortcode('lang_switcher', 'polylang_switcher_shortcode');

    

Custom Flags

Upload custom flag images to /wp-content/polylang/ using the naming convention of the language locale (e.g., en_US.png, fr_FR.png). Then flush rewriting rules in Settings > Permalinks.