The filter_block_kses() WordPress PHP function sanitizes a parsed block by filtering out non-allowable HTML from block attribute values.
Usage
To use filter_block_kses(), you will pass in the parsed block object, the allowed HTML context or an array of allowed HTML elements and attributes, and optionally, an array of allowed URL protocols.
$clean_block = filter_block_kses($block, 'post');
In this example, $block
represents the parsed block object and ‘post’ is the context for the allowed HTML. The function returns a sanitized block object, $clean_block
.
Parameters
- $block (WP_Block_Parser_Block) – The parsed block object that needs sanitizing.
- $allowed_html (array | string) – An array of allowed HTML elements and attributes, or a context name such as ‘post’. For the list of accepted context names, see wp_kses_allowed_html().
- $allowed_protocols (string) – Optional parameter. This is an array of allowed URL protocols. By default, it uses the result of wp_allowed_protocols().
More information
See WordPress Developer Resources: filter_block_kses()
This function is crucial in maintaining the security and integrity of your WordPress site by ensuring that only allowed HTML and URL protocols are included in your block attributes.
Examples
Sanitize a block with a post context
This code sanitizes a block with the ‘post’ context, which allows only HTML suitable for post content.
$block = new WP_Block_Parser_Block('my-block', array('content' => '<a href="http://example.com">Example</a>')); $clean_block = filter_block_kses($block, 'post');
Allow only specific HTML elements
In this case, we’re allowing only <p>
and <a>
tags in the block content.
$allowed_html = array('a' => array(), 'p' => array()); $block = new WP_Block_Parser_Block('my-block', array('content' => '<p><a href="http://example.com">Example</a></p>')); $clean_block = filter_block_kses($block, $allowed_html);
Using an array of allowed protocols
This code defines a custom set of allowed URL protocols and uses them to sanitize a block.
$protocols = array('http', 'https', 'mailto'); $block = new WP_Block_Parser_Block('my-block', array('content' => '<a href="mailto:[email protected]">Example</a>')); $clean_block = filter_block_kses($block, 'post', $protocols);
Sanitize a block with a custom context
This code sanitizes a block with a custom context of ‘custom’.
$block = new WP_Block_Parser_Block('my-block', array('content' => '<a href="http://example.com">Example</a>')); $clean_block = filter_block_kses($block, 'custom');
Sanitize a block with no URL protocols allowed
In this example, no URL protocols are allowed, so any links in the block content will be removed.
$block = new WP_Block_Parser_Block('my-block', array('content' => '<a href="http://example.com">Example</a>')); $clean_block = filter_block_kses($block, 'post', array());