Banner,Software,Development.,3d,Laptop,With,Programming,Icon.,Web,Coding

How I Changed the HTML Tag’s lang Attribute Using WPCode

At kosu.blog, I include not only Japanese content but also a few English articles. I had previously set the site’s language to English and used the post template to determine whether the content was in Japanese. Then, I used JavaScript to dynamically change the lang attribute of the <html> tag to “ja” for Japanese content or leave it as “en” for English.

However, since this method relies on JavaScript to modify the attribute dynamically when the page is displayed, search engines register the source code before the change takes effect. As a result, there was a risk that the content could be indexed under an unintended language. To ensure the correct language is set from the moment the page is loaded, I needed a more reliable solution.

Modifying WordPress Code with WPCode

To achieve this, I needed to modify WordPress’s code, but this was easily done using the WPCode plugin. When WordPress generates the <html> tag, it retrieves the site’s language setting and assigns it to the lang attribute. The default code looks something like this:

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

To override this, I used a WordPress filter hook. Since I use an English template for certain posts and have structured the English homepage under a page named “english”, I modified the hook to set the lang attribute to “en” whenever one of these two pages is displayed. The site’s default language remains Japanese (“ja”), but it switches to English (“en”) when these specific pages are viewed.

add_filter( 'language_attributes', function($lang_attributes) {
	if (is_single()) {
		$template = get_page_template_slug();
		if ($template == 'english-post') {
			$lang_attributes = "lang=\"en\"";
		}
	} else {
		$pagename = get_query_var( 'pagename' );
		if ($pagename == 'english') {
			$lang_attributes = "lang=\"en\"";
		}
	}
	return "$lang_attributes";
});

Implementing the Change with WPCode

To apply this modification, I installed the WPCode plugin and added a new custom snippet. Since WPCode allows you to insert PHP snippets, I simply pasted the above code into a new Custom Snippet. This method is completely free, so there’s no need to upgrade to the Pro version.

By using WPCode, I was able to ensure that the lang attribute is correctly set from the moment the page loads, improving both search engine indexing and user experience.

こすぶろをもっと見る

今すぐ購読し、続きを読んで、すべてのアーカイブにアクセスしましょう。

続きを読む