Using esc_html__ to escape and translate HTML entities in WordPress
The esc_html__
function in WordPress is used to escape and translate a string. It is useful for preventing cross-site scripting (XSS) attacks by escaping the string to make it safe for output in HTML. Additionally, it can also be used to translate the string into different languages, making it a useful tool for internationalization and localization of WordPress themes and plugins.
Parameters accepted by the WordPress esc_html__ function
$text
(string, required): Text to translate.$domain
(string, optional, default value: ‘default’): Text domain. Unique identifier for retrieving translated strings. Default value is ‘default’.
The function returns a string, which is the translated text.
Examples
How to use esc_html__ to escape and translate a string
<?php
$translated_string = esc_html__( 'Hello, World!', 'text-domain' );
echo $translated_string;
?>
The code snippet uses the esc_html__
function to escape and translate the string ‘Hello, World!’ using the text domain ‘text-domain’. The function ensures that the output is safe for use in HTML and translates the string for localization.
How to use esc_html__ to escape and translate a string with placeholders
<?php
$name = 'John';
$greeting = esc_html__( 'Hello, %s!', 'text-domain' );
$translated_greeting = sprintf( $greeting, $name );
echo $translated_greeting;
?>
The code snippet demonstrates using the esc_html__
function to escape and translate a string with a placeholder (%s) for the name variable. The sprintf function is used to replace the placeholder with the actual value of the $name variable.
How to use esc_html__ to escape and translate a string within a loop
<?php
$names = array( 'John', 'Jane', 'Doe' );
foreach ( $names as $name ) {
$greeting = esc_html__( 'Hello, %s!', 'text-domain' );
$translated_greeting = sprintf( $greeting, $name );
echo $translated_greeting . '<br>';
}
?>
In this example, the esc_html__
function is used within a loop to escape and translate a greeting string for each name in the $names array. The sprintf function is used to replace the placeholder with the actual value of each name, and the translated greeting is echoed with a line break after each iteration.
Conclusion
In conclusion, the esc_html__
function is a vital tool for developers looking to ensure the security and integrity of their WordPress plugins and themes. By escaping and translating text for safe output, this function helps to prevent cross-site scripting attacks and maintain the overall quality of the user experience. Incorporating esc_html__
into your development workflow is a best practice that should not be overlooked. With its ability to handle translations and sanitize user input, it is a versatile and essential function for any WordPress project.