Using WordPress ‘filter_block_content()’ PHP function

The filter_block_content() WordPress PHP function filters and sanitizes block content. It removes non-allowable HTML from parsed block attribute values.

Usage

Here’s a simple usage example:

$text = "<h1>Hello World!</h1><script>alert('Nope.');</script>";
$filtered_text = filter_block_content($text);
echo $filtered_text; // Outputs: <h1>Hello World!</h1>

Parameters

  • $text (string, Required): Text that may contain block content.
  • $allowed_html (array | string, Optional): 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. Default is ‘post’.
  • $allowed_protocols (string, Optional): Array of allowed URL protocols. Defaults to the result of wp_allowed_protocols(). Default is an empty array.

More information

See WordPress Developer Resources: filter_block_content()

This function is part of the core WordPress functionality and is not deprecated.

Examples

Filtering Basic HTML Content

$text = "<h1>Welcome!</h1><p>This is my site.</p><script>badCode();</script>";
$clean_text = filter_block_content($text);
echo $clean_text; // Outputs: <h1>Welcome!</h1><p>This is my site.</p>

This example filters out the script tag from the text.

Allowing Custom HTML Elements

$text = "<custom>Hello World!</custom>";
$allowed_html = array( 'custom' => array() );
$clean_text = filter_block_content($text, $allowed_html);
echo $clean_text; // Outputs: <custom>Hello World!</custom>

This example allows the ‘custom’ HTML tag in the content.

Specifying Context for Allowed HTML

$text = "<aside>This is a sidebar.</aside>";
$clean_text = filter_block_content($text, 'sidebar');
echo $clean_text; // Outputs: <aside>This is a sidebar.</aside>

This example uses ‘sidebar’ as the context for allowed HTML elements.

Allowing Specific URL Protocols

$text = "<a href='customprotocol://example.com'>Link</a>";
$allowed_protocols = array('http', 'https', 'customprotocol');
$clean_text = filter_block_content($text, 'post', $allowed_protocols);
echo $clean_text; // Outputs: <a href='customprotocol://example.com'>Link</a>

This example allows the ‘customprotocol’ URL protocol in the content.

Using Default Values

$text = "<h1>Hello World!</h1><script>alert('Nope.');</script>";
$clean_text = filter_block_content($text);
echo $clean_text; // Outputs: <h1>Hello World!</h1>

This example uses default values for $allowed_html and $allowed_protocols.