The esc_textarea() WordPress PHP function is used for escaping text values within textarea elements.
Usage
Here’s an example showing how to use this function:
$text = "Hello <b>world!</b>"; echo '<textarea>' . esc_textarea($text) . '</textarea>';
In this case, the output will be:
<textarea>Hello <b>world!</b></textarea>
Parameters
- $text (string) – This parameter is the text you want to escape.
More information
See WordPress Developer Resources: esc_textarea()
This function has been implemented since WordPress version 3.1. For further details, you can refer to the source code in wp-includes/formatting.php.
Examples
Using esc_textarea() with a Form
If you’re creating a form, you can use esc_textarea() to make sure user input is safely displayed:
$text = $_POST['user_text']; echo '<textarea>' . esc_textarea($text) . '</textarea>';
This code takes user input from a form POST and safely outputs it into a textarea element.
Escaping HTML Characters
esc_textarea() will escape HTML characters in your string. For instance:
$text = "<script>alert('Hello!');</script>"; echo '<textarea>' . esc_textarea($text) . '</textarea>';
This will output:
<textarea><script>alert('Hello!');</script></textarea>
As you can see, esc_textarea() helps prevent any potential XSS attacks by escaping HTML characters.
Handling Newlines
esc_textarea() also preserves newlines in your text:
$text = "Line 1\nLine 2"; echo '<textarea>' . esc_textarea($text) . '</textarea>';
This will output:
<textarea>Line 1 Line 2</textarea>
Here, esc_textarea() preserves the newline character in the output.
Escaping Special Characters
esc_textarea() can handle special characters, like ampersands, in your text:
$text = "Fish & Chips"; echo '<textarea>' . esc_textarea($text) . '</textarea>';
This will output:
<textarea>Fish & Chips</textarea>
In this case, esc_textarea() escapes the ampersand to prevent it from being interpreted as the start of an HTML entity.
Using with WordPress Options API
You can use esc_textarea() when retrieving options with the WordPress Options API:
$option = get_option('my_option'); echo '<textarea>' . esc_textarea($option) . '</textarea>';
This ensures that the option value is safely escaped before being output in the textarea.