Set different language for some WordPress posts
You might need to change the default language for some of your posts written in another language. Assuming you have a blog category designated for this different language, you could use the following snippet:
// Add a filter to modify the language attributes
add_filter('language_attributes', function($lang) {
// Check if the current page is a single post page
if(is_single()) {
// Retrieve the categories of the post
$categories = get_the_category();
// Loop through each category
foreach($categories as $category) {
// Check if the category slug matches 'czech-articles'
if($category->slug == 'czech-articles') {
// If a match is found, replace 'en-GB' with 'cs' in the language attributes
$lang = str_replace('en-GB', 'cs', $lang);
// Break the loop as we found the category we were looking for
break;
}
}
}
// Return the modified (or unmodified) language attributes
return $lang;
});