Modify the language attribute based on category in WordPress

How to modify the language attribute in your Wordpress theme using a specific value

Novembre 7, 2019

I have a blog mainly written in English. Sometimes I make posts in Italian. When I make a post in Italian I classify it within a category named “In Italiano“. This category collects all the posts in italian language.

The header.php file of the theme has this HTML header tag:

<html <?php language_attributes(); ?>>

This code outputs the language from the WordPress configuration, which is correctly:

<html lang="en-US">

But in pages in Italian language this attribute is wrong, since the body content of the HTML page is in Italian. So, this attribute could be marked as an error for Google crawler since the W3C HTML validator raises a warning noting the difference between declared language and used language.

To fix this problem I’ve added this small function that applies a filter to the language_attributes function, modifying the result accordingly:

//
// set language attribute of the main <html> tag based on category value
function new_language_attributes($lang){
	if(is_single()) {
		$ar = get_the_category();
		foreach($ar as $c) {
			if($c->slug=='in-italiano') {
				return "lang=\"it\"";
			}
		}
	}
	return $lang;
}
add_filter('language_attributes', 'new_language_attributes');

The add_filter function allows to hook a specific WordPress function and modify how it works. So, with this code above we tell WordPress that when it calls the language_attributes function (as did in the <html> head tag) after the function is completed it has to pass the result to our new_language_attributes function that could change the result if needed.

Is attribute lang useful for SEO purposes?

Googling around the web to search if this tip is useful I’ve found that it isn’t clear and probably it’s not necessary (I’ve read it in this article dated 2016), since Google detects language by itself and doesn’t use the lang attribute of the <html> tag.

However trying to remove all Warnings and Errors in W3C Validator is always a very difficult struggle and – in my experience – it’s a way to go only if you have some big error in your HTML and you can’t find it with your eyes, for example when you can’t find the closing <div> in a complex template and it causes many layout problems on your page.

Author

PHP expert. Wordpress plugin and theme developer. Father, Maker, Arduino and ESP8266 enthusiast.