WordPress | WPML Body class or data-atribute based on language
In a wordpress project, For a design request, i need to adjust minimal differences that are showed on main menù when user switchs languages.
By default, wordpress and wpml, don’t adds references about the actual active language.
So i want to add as body class the language code based on the active language.
Let’s start !
Navigate to your theme root, and open the file function.php
At bottom of this file add :
/* WPML - Add language Class as Body Class */ add_filter('body_class', 'append_language_class'); function append_language_class($classes){ $classes[] = 'lang-'.ICL_LANGUAGE_CODE; //or however you want to name your class based on the language code return $classes; }
I choose to add a class made by “lang-” text and the active language code, so in Italian will be “lang-it” in english “lang-en”
From now i can style different css based on language, without worrie about that the modifies effected on other languages.
es:
body.lang-en{ .nav-full_active ul ul{ margin-left: 16.13rem; } } body.lang-it{ .nav-full_active ul ul{ margin-left: 16.13rem; } }
Here un example of “before” and “after” body class:
Before
After
And here if you need to add a data-attribute:
add_filter('body_class', 'append_language_class'); function append_language_class($classes){ $classes[] = '" data-lang="'.ICL_LANGUAGE_CODE; return $classes; }
That’s
All