My posts also serve as an archive for myself, because simply, sometimes I had to research solutions I’ve already applied once in WordPress – but on which website was it and how was it done?
So today I needed to switch a header image on a multilingual website according to the language. It was integrated as CSS background image, and the plugin Polylang added a language class only to the articles tag, not to the body tag, so out of reach for my header. I immediately found a few solutions that make it possible, using different approaches, and all working in child-themes or even with pure CSS. I want to collect all of them here because in different situations I might prefer or even need one or the other.
Solution #1: Changing the CSS Background Image by adding a Language Class to the Body Tag
Adding this code to your child-theme’s function.php is adding a class name as ‘de-DE’ to the body tag.
1 2 3 4 5 |
add_filter('body_class', 'my_custom_body_class', 10, 2); function my_custom_body_class($classes) { $classes[] = get_bloginfo('language'); return $classes; } |
Now we can address any element depending on the set language through CSS.
1 2 |
body.en-US #headerimage {background-image: url(headerimage-en.jpg);} body.de-DE #headerimage {background-image: url(headerimage-de.jpg);} |
Thanks to namoras for sharing.
Solution #2: Using PHP If-Conditions directly in the Template files
This solution works directly in the template files without adding a class to the body element, but directly addressing everything with conditions. Can be an easier and more flexible approach in some scenarios, can be much effort in others.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php $currentlang = get_bloginfo('language'); if($currentlang=="en-US"): ?> <!-- Put your code for english here. --> <?php elseif($currentlang=="de-DE"): ?> <!-- Put your code for german here. --> <?php else: ?> <!-- Put your code for any other here. --> <?php endif; ?> |
Thanks to ChowKaiDeng for sharing.
Solution #3: Calling current Language directly with PHP
Even more elegant and short, we can add the language code directly anywhere we want through the WordPress function echo pll_current_language(). In this approach we need to name the header images accordingly, as header-it.jpg, header-fr.jpg etc.
1 |
<img src="images/header-<?php echo pll_current_language(); ?>.jpg" alt="header" /> |
Thanks to fmarie for sharing.
Top-Solution #4: The most elegant CSS2 :lang Selector
Well, this is something. The author of Polylang mentioned it in another answer, and it seems to be the perfect solution for most if not even all cases.
1 2 |
#headerimage:lang(de) {background-image: url(headerimage-de.jpg);} #headerimage:lang(en) {background-image: url(headerimage-en.jpg);} |