How to Dynamically Update the HTML Lang Attribute in WordPress Using functions.php

WordPress and dynamically update the <html lang=""> attribute for English and French pages by editing your functions.php file.

 

function swigroup_custom_language_attributes( $output ) {
// Get the current URL
$url_path = $_SERVER['REQUEST_URI'];

// Default language
$lang = 'en-US';

// If URL contains /fr/, set lang to French
if ( strpos( $url_path, '/fr/' ) !== false ) {
$lang = 'fr-FR';
}

// Return the full attribute
return 'lang="' . esc_attr( $lang ) . '"';
}
add_filter( 'language_attributes', 'swigroup_custom_language_attributes' );