parse_blocks()

最后更新于:2021-11-27 18:37:21

parse_blocks( string$content)

Parses blocks out of a content string.

参数

$content

(string) (Required) Post content.

响应

(array[]) Array of parsed block objects.

源文件

文件: gc-includes/blocks.php

function parse_blocks( $content ) {
	/**
	 * Filter to allow plugins to replace the server-side block parser
	 *
	 * @since 5.0.0
	 *
	 * @param string $parser_class Name of block parser class.
	 */
	$parser_class = apply_filters( 'block_parser_class', 'GC_Block_Parser' );

	$parser = new $parser_class();
	return $parser->parse( $content );
}
<?php
function gcdocs_display_post_youtube_block() {

	global $post;
	
	$blocks = parse_blocks( $post->post_content );
	
	foreach ( $blocks as $block ) {

		// YouTube's block name
		if ( 'core-embed/youtube' === $block['blockName'] ) {
			
			echo apply_filters( 'the_content', render_block( $block ) );
			
			break;
			
		}
		
	}
	
}

?>
array ( 
	0 => array ( 
		'blockName' => 'core/paragraph', 
		'attrs' => array ( 
			'textColor' => 'vivid-red', 
			'backgroundColor' => 'luminous-vivid-amber',
		), 
		'innerBlocks' => array (
			/* Child blocks if they exists (used in Column Block for example) */
		), 
		'innerHTML' => 'This is a block content!', 
		'innerContent' => array (
			0 => 'This is a block content!',
		), 
	),
)
Array
(
  [0] => Array
    (
      [blockName] => core/paragraph
      [attrs] => Array
        (
          [placeholder] => Summary
          [textColor] => accent
          [backgroundColor] => secondary
        )
      [innerBlocks] => Array()
      [innerHTML] => <p class="has-text-color has-background has-accent-color has-secondary-background-color">This is a new paragraph.</p>
      [innerContent] => Array
        (
          [0] => <p class="has-text-color has-background has-accent-color has-secondary-background-color">This is a new paragraph.</p>
        )
      )
)