wpseek.com
A WordPress-centric search engine for devs and theme authors



wp_strip_custom_css_from_blocks › WordPress Function

Since7.0.0
Deprecatedn/a
wp_strip_custom_css_from_blocks ( $content )
Access:
  • private
Parameters:
  • (string) $content Post content to filter, expected to be escaped with slashes.
    Required: Yes
Returns:
  • (string) Filtered post content with block custom CSS removed.
Defined at:
Codex:

Strips custom CSS (`style.css` in attributes) from all blocks in post content.

Uses WP_Block_Parser::next_token to scan block tokens and surgically replace only the attribute JSON that changed — no parse_blocks() + serialize_blocks() round-trip needed.


Source

function wp_strip_custom_css_from_blocks( $content ) {
	if ( ! has_blocks( $content ) ) {
		return $content;
	}

	$unslashed = stripslashes( $content );

	$parser           = new WP_Block_Parser();
	$parser->document = $unslashed;
	$parser->offset   = 0;
	$end              = strlen( $unslashed );
	$replacements     = array();

	while ( $parser->offset < $end ) {
		$next_token = $parser->next_token();

		if ( 'no-more-tokens' === $next_token[0] ) {
			break;
		}

		list( $token_type, , $attrs, $start_offset, $token_length ) = $next_token;

		$parser->offset = $start_offset + $token_length;

		if ( 'block-opener' !== $token_type && 'void-block' !== $token_type ) {
			continue;
		}

		if ( ! isset( $attrs['style']['css'] ) ) {
			continue;
		}

		// Remove css and clean up empty style.
		unset( $attrs['style']['css'] );
		if ( empty( $attrs['style'] ) ) {
			unset( $attrs['style'] );
		}

		// Locate the JSON portion within the token.
		$token_string   = substr( $unslashed, $start_offset, $token_length );
		$json_rel_start = strcspn( $token_string, '{' );
		$json_rel_end   = strrpos( $token_string, '}' );

		$json_start  = $start_offset + $json_rel_start;
		$json_length = $json_rel_end - $json_rel_start + 1;

		// Re-encode attributes. If attrs is now empty, remove JSON and trailing space.
		if ( empty( $attrs ) ) {
			// Remove the trailing space after JSON.
			$replacements[] = array( $json_start, $json_length + 1, '' );
		} else {
			$replacements[] = array( $json_start, $json_length, serialize_block_attributes( $attrs ) );
		}
	}

	if ( empty( $replacements ) ) {
		return $content;
	}

	// Build the result by splicing replacements into the original string.
	$result = '';
	$was_at = 0;

	foreach ( $replacements as $replacement ) {
		list( $offset, $length, $new_json ) = $replacement;
		$result                            .= substr( $unslashed, $was_at, $offset - $was_at ) . $new_json;
		$was_at                             = $offset + $length;
	}

	if ( $was_at < $end ) {
		$result .= substr( $unslashed, $was_at );
	}

	return addslashes( $result );
}