Internal GitBook note: These snippets are currently the most up to date versions available. Please keep all the scripts and code up to date. Whenever you make changes to the scripts in the project and it's generally usable and doesn't contan any project based code, update it here as well. This way we have this version right here always fresh to use in the next project.
/**
* Show Polylang Languages with Custom Markup (for accessibility reasons)
*/
function pll_the_languages_a11y( $class = '' ) { // phpcs:ignore
if ( ! function_exists( 'pll_the_languages' ) ) return; // phpcs:ignore
// Gets the pll_the_languages() raw code
$languages = pll_the_languages( array(
'display_names_as' => 'name', // Has to be name, so we can print out both slug and name
'hide_if_empty' => 0,
'hide_if_no_translation' => 0,
'raw' => 1,
'echo' => 1,
'show_flags' => 0,
'hide_current' => 0,
) );
$output = '';
// Checks if the $languages is not empty
if ( ! empty( $languages ) ) {
// Creates the $output variable with languages container
$output = '<div role="region" class="language-switcher' . ( $class ? ' ' . $class : '' ) . '" aria-label="' . esc_html( ask__( 'Saavutettavuus: Valitse kieli' ) ) . '"><ul>';
// Runs the loop through all languages
foreach ( $languages as $language ) {
// Variables containing language data
$id = $language['id'];
$slug = $language['slug'];
$name = $language['name'];
$url = $language['url'];
$current = $language['current_lang'];
$no_translation = $language['no_translation'];
// HTML Markup example from the recmmended source:
// https://www.saavutettavuusvaatimukset.fi/
// Checks if the page has translation in this language
// if ( ! $no_translation ) {
// Check if it's current language
if ( $current ) {
$output .= '<li lang="' . $slug . '" class="lang-item lang-item-' . $slug . ' current-lang">
<a hreflang="' . $slug . '" aria-current="page" href="' . $url . '">
<span class="screen-reader-text">' . ask__( 'Saavutettavuus: Suomi: Vaihda kieli Suomeksi' ) . '</span>
<span class="site-lang-label" aria-hidden="true">' . ucfirst( $slug ) . '</span>
</a></li>';
} else {
$output .= '<li lang="' . $slug . '" class="lang-item lang-item-' . $slug . '">
<a hreflang="' . $slug . '" href="' . $url . '">
<span class="screen-reader-text">' . $name . ': ' . ask__( 'Saavutettavuus: Vaihda kieli kieleen' ) . ' ' . $name . '</span>
<span class="site-lang-label" aria-hidden="true">' . ucfirst( $slug ) . '</span>
</a></li>';
}
// }
}
$output .= '</ul></div>';
}
return $output;
}
<?php if ( function_exists( 'pll_the_languages' ) ) : ?>
<?php echo pll_the_languages_a11y($class = 'nav-language'); // phpcs:ignore ?>
<?php endif; ?>