The attribute_escape WordPress PHP filter is used to clean and escape a string for output in an HTML attribute, ensuring safe and valid output.
Usage
$filtered_text = apply_filters('attribute_escape', $safe_text, $text); // your custom code here return $filtered_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: attribute_escape
Examples
Adding a custom prefix to an attribute value
function custom_attribute_escape($safe_text, $text) { return 'custom-prefix-' . $safe_text; } add_filter('attribute_escape', 'custom_attribute_escape', 10, 2);
Converting all text to uppercase
function uppercase_attribute_escape($safe_text, $text) { return strtoupper($safe_text); } add_filter('attribute_escape', 'uppercase_attribute_escape', 10, 2);
Replacing spaces with underscores
function replace_spaces_attribute_escape($safe_text, $text) { return str_replace(' ', '_', $safe_text); } add_filter('attribute_escape', 'replace_spaces_attribute_escape', 10, 2);
Adding a custom suffix to an attribute value
function custom_suffix_attribute_escape($safe_text, $text) { return $safe_text . '-custom-suffix'; } add_filter('attribute_escape', 'custom_suffix_attribute_escape', 10, 2);
Replacing specific characters with their HTML entities
function replace_chars_attribute_escape($safe_text, $text) { $replacements = array( '©' => '©', '®' => '®', ); return strtr($safe_text, $replacements); } add_filter('attribute_escape', 'replace_chars_attribute_escape', 10, 2);