函数文档

has_blocks()

💡 云策文档标注

概述

has_blocks() 函数用于检测文章或内容字符串是否包含区块,它优先考虑性能而非严格准确性,通过模式匹配而非结构验证来快速判断。对于需要精确解析的场景,建议使用 parse_blocks() 函数。

关键要点

  • 函数接受可选参数 $post,可以是内容字符串、文章 ID、WP_Post 对象或 null(默认使用全局 $post),返回布尔值表示是否包含区块。
  • 内部实现中,如果 $post 不是字符串,会通过 get_post() 获取文章对象并提取 post_content 进行检测。
  • 检测基于字符串包含特定模式(如 '

    if ( has_blocks() ) {
        // Do something.
    }

  • Skip to note 4 content

    1. We can use this function to pass a flag to indicate if content has blocks when we have decoupled environment, where WP is backend and frontend is implemented in some other language.

    2. We can convert (parse) block output as per our requirement and pass it in the API. While, converting it can be useful to check if the content has any block. This will let us pass content efficiently by implementing parsing when it is necessary.

    class WPDocs_Custom_Block_Parse {
    
    	function parse() {
    		// Do something
      	}
    }
    
    function wpdocs_custom_block_parser() {
    	return 'WPDocs_Custom_Block_Parse';
    }
    
    /**
     * In the implementation check if content has block
     */
    if ( has_blocks( $post_content ) ) {
    	add_filter( 'block_parser_class', 'wpdocs_custom_block_parser' );
    	$response_content = parse_blocks( $content );
    	remove_filter( 'block_parser_class', 'wpdocs_custom_block_parser' );
    }