Change WordPress html lang attribute based on template filename

This might be a rather seldom needed feature, but I need it for my blog (yes, this one).

As I am writing my blog posts in both english (for technical stuff) and german (for all the other stuff), I need to change the html’s lang attribute  to display the correct language code.

How am I using it?

I am using an extra template file for my english blog posts. The filename is single-english.php .  So whenever I am writing an english post like this one, I select the correct template for it.

This image shows my Template selector, which lets me chose between the standard template and the english post template.

Override WordPress‘ language_attributes function

To change the html’s lang attribute , we need to override the language_attributes  function. To do so, I inserted the following code into my theme’s functions.php  file.

Within this function, I get the page template used by the current post. I then check whether my filename is present in the returned template path. If so, I set the variable $lang  to en-US . The standard language is have pre-set is de-DE .

Veröffentlicht von

Christian Hänsel

Web-Entwickler, SEO-Experte. Ich liebe technisches SEO, die Entwicklung von neuen Ideen und alles rund um das Internet... ja, ich habe mein Hobby zum Beruf gemacht und gehe auch Montags gerne zur Arbeit.

Kommentar verfassen