The language_attributes WordPress PHP Filter allows you to modify the language attributes displayed in the ‘html’ tag.
Usage
add_filter('language_attributes', 'your_custom_function', 10, 2); function your_custom_function($output, $doctype) { // your custom code here return $output; }
Parameters
$output
(string) – A space-separated list of language attributes.$doctype
(string) – The type of HTML document (xhtml|html).
More information
See WordPress Developer Resources: language_attributes
Examples
Add a custom language attribute
Add a custom language attribute called “data-custom-lang”.
add_filter('language_attributes', 'add_custom_language_attribute', 10, 2); function add_custom_language_attribute($output, $doctype) { $output .= ' data-custom-lang="en-US"'; return $output; }
Change the language attribute
Change the language attribute value to “en-GB”.
add_filter('language_attributes', 'change_language_attribute', 10, 2); function change_language_attribute($output, $doctype) { $output = str_replace('en-US', 'en-GB', $output); return $output; }
Remove the language attribute
Remove the language attribute from the ‘html’ tag.
add_filter('language_attributes', 'remove_language_attribute', 10, 2); function remove_language_attribute($output, $doctype) { $output = ''; return $output; }
Add a custom attribute based on the post’s language
Add a custom attribute called “data-post-lang” based on the post’s language.
add_filter('language_attributes', 'add_post_language_attribute', 10, 2); function add_post_language_attribute($output, $doctype) { global $post; $post_language = get_post_meta($post->ID, 'post_language', true); $output .= ' data-post-lang="' . esc_attr($post_language) . '"'; return $output; }
Change the doctype to XHTML
Change the doctype of the ‘html’ tag to XHTML.
add_filter('language_attributes', 'change_doctype_to_xhtml', 10, 2); function change_doctype_to_xhtml($output, $doctype) { if ($doctype == 'html') { $doctype = 'xhtml'; } $output = preg_replace('/(<!DOCTYPE\s+html)/i', '<!DOCTYPE ' . $doctype, $output); return $output; }