To escape output in PHP within WordPress, you can use the esc_html()
function to convert special characters to their HTML entities. This is useful for preventing XSS (Cross-Site Scripting) attacks by ensuring that any user-provided data is properly sanitized before being outputted to the webpage.
Here’s an example of how to use esc_html()
:
<?php
$my_variable = "This is <strong>bold</strong> text.";
echo esc_html($my_variable);
?>
In the example above, the output will be:
This is <strong>bold</strong> text.
As you can see, the <strong>
tag has been converted to <strong>
to prevent it from being interpreted as HTML by the browser.
Note that there are other escaping functions available in WordPress, such as esc_attr()
for escaping attributes and esc_url()
for escaping URLs. You should choose the appropriate function based on the context in which you are using the output.