Using WordPress ‘filter_block_kses_value()’ PHP function

The filter_block_kses_value() WordPress PHP function filters and sanitizes a parsed block attribute value to remove non-allowable HTML.

Usage

To use filter_block_kses_value(), you pass in the attribute value you want to filter and specify allowed HTML elements and attributes. Optionally, you can also specify the allowed URL protocols.

$filtered_value = filter_block_kses_value( $value, $allowed_html, $allowed_protocols );

Parameters

  • $value (string) – The attribute value to filter.
  • $allowed_html (array | string) – An array of allowed HTML elements and attributes, or a context name such as ‘post’. See wp_kses_allowed_html() for the list of accepted context names.
  • $allowed_protocols (string – Optional) – Array of allowed URL protocols. Defaults to the result of wp_allowed_protocols(). Default: array()

More information

See WordPress Developer Resources: filter_block_kses_value()

Examples

Filtering a Simple String

This code filters a simple string attribute.

$value = '<script>alert("Hello!")</script>';
$allowed_html = 'post'; // Allow only post context
$filtered_value = filter_block_kses_value($value, $allowed_html);

Allowing Specific HTML Elements

This example allows only specific HTML elements.

$value = '<div><p>Hello World!</p></div>';
$allowed_html = array( 'p' ); // Allow only 'p' tags
$filtered_value = filter_block_kses_value($value, $allowed_html);

Allowing Specific HTML Attributes

This code allows specific HTML attributes.

$value = '<a href="https://example.com" target="_blank" rel="noopener">Example</a>';
$allowed_html = array( 'a' => array( 'href' => true, 'target' => true )); // Allow 'a' tags with 'href' and 'target' attributes
$filtered_value = filter_block_kses_value($value, $allowed_html);

Allowing Specific URL Protocols

This example allows specific URL protocols.

$value = '<a href="ftp://example.com">Example</a>';
$allowed_html = array( 'a' => array( 'href' => true ));
$allowed_protocols = array( 'ftp' ); // Allow only 'ftp' protocol
$filtered_value = filter_block_kses_value($value, $allowed_html, $allowed_protocols);

Using Default URL Protocols

In this code, we use the default URL protocols.

$value = '<a href="ftp://example.com">Example</a>';
$allowed_html = array( 'a' => array( 'href' => true ));
$filtered_value = filter_block_kses_value($value, $allowed_html);