The esc_textarea WordPress PHP filter cleans and escapes text for output in a textarea element.
Usage
add_filter('esc_textarea', 'your_custom_function', 10, 2); function your_custom_function($safe_text, $text) { // your custom code here return $safe_text; }
Parameters
$safe_text
(string) – The text after it has been escaped.$text
(string) – The text prior to being escaped.
More information
See WordPress Developer Resources: esc_textarea
Examples
Limit Text Length
Limit the number of characters displayed in the textarea to 200 characters.
add_filter('esc_textarea', 'limit_text_length', 10, 2); function limit_text_length($safe_text, $text) { $limited_text = substr($safe_text, 0, 200); return $limited_text; }
Replace URLs
Replace URLs within the textarea content with the text “Link removed”.
add_filter('esc_textarea', 'replace_urls', 10, 2); function replace_urls($safe_text, $text) { $replaced_text = preg_replace('/(http|https):\/\/\S+/', 'Link removed', $safe_text); return $replaced_text; }
Remove Line Breaks
Remove line breaks from the textarea content.
add_filter('esc_textarea', 'remove_line_breaks', 10, 2); function remove_line_breaks($safe_text, $text) { $no_line_breaks = str_replace(array("\r\n", "\r", "\n"), '', $safe_text); return $no_line_breaks; }
Convert Hashtags to Links
Convert hashtags in the textarea content to clickable links.
add_filter('esc_textarea', 'convert_hashtags_to_links', 10, 2); function convert_hashtags_to_links($safe_text, $text) { $linked_hashtags = preg_replace('/#(\w+)/', '<a href="https://example.com/hashtag/$1">#$1</a>', $safe_text); return $linked_hashtags; }
Add Custom Prefix
Add a custom prefix “Note: ” to the textarea content.
add_filter('esc_textarea', 'add_custom_prefix', 10, 2); function add_custom_prefix($safe_text, $text) { $prefixed_text = 'Note: ' . $safe_text; return $prefixed_text; }