has_block

函数
has_block ( $block_name, $post = null )
参数
  • (string) $block_name Full block type to look for.
    Required:
  • (int|string|WP_Post|null) $post Optional. Post content, post ID, or post object. Defaults to global $post.
    Required:
    Default: null
返回值
  • (bool) Whether the post content contains the specified block.
相关
  • parse_blocks()
定义位置
相关方法
has_blocksparse_blocksdo_blocks_flatten_blocksserialize_block
引入
5.0.0
弃用
-

has_block: 这个函数用于检查一个文章或页面的内容中是否存在特定的块: 该函数将块的类型作为一个参数,如果该块存在,则返回一个布尔值为true,否则为false。

确定$post或一个字符串是否包含一个特定的块类型。

这个测试对性能进行了优化,而不是严格的准确性,它检测了块类型是否存在,但没有验证其结构,也没有检查可重用的块。对于严格的准确性,你应该在文章内容上使用块分析器。

function has_block( $block_name, $post = null ) {
	if ( ! has_blocks( $post ) ) {
		return false;
	}

	if ( ! is_string( $post ) ) {
		$wp_post = get_post( $post );
		if ( $wp_post instanceof WP_Post ) {
			$post = $wp_post->post_content;
		}
	}

	/*
	 * Normalize block name to include namespace, if provided as non-namespaced.
	 * This matches behavior for WordPress 5.0.0 - 5.3.0 in matching blocks by
	 * their serialized names.
	 */
	if ( false === strpos( $block_name, '/' ) ) {
		$block_name = 'core/' . $block_name;
	}

	// Test for existence of block by its fully qualified name.
	$has_block = false !== strpos( $post, '<!-- wp:' . $block_name . ' ' );

	if ( ! $has_block ) {
		/*
		 * If the given block name would serialize to a different name, test for
		 * existence by the serialized form.
		 */
		$serialized_block_name = strip_core_block_namespace( $block_name );
		if ( $serialized_block_name !== $block_name ) {
			$has_block = false !== strpos( $post, '<!-- wp:' . $serialized_block_name . ' ' );
		}
	}

	return $has_block;
}

常见问题

FAQs
查看更多 >