has_block()
最后更新于:2021-11-27 04:38:33
has_block( string$block_name, int|string|GC_Post|null$post=null)Determine whether a $post or a string contains a specific block type.
参数
- $block_name
-
(string) (Required) Full block type to look for.
- $post
-
(int|string|GC_Post|null) (Optional) Post content, post ID, or post object. Defaults to global $post.
Default value: null
响应
(bool) Whether the post content contains the specified block.
源文件
文件: gc-includes/blocks.php
function has_block( $block_name, $post = null ) {
if ( ! has_blocks( $post ) ) {
return false;
}
if ( ! is_string( $post ) ) {
$gc_post = get_post( $post );
if ( $gc_post instanceof GC_Post ) {
$post = $gc_post->post_content;
}
}
/*
* Normalize block name to include namespace, if provided as non-namespaced.
* This matches behavior for GeChiUI 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, '<!-- gc:' . $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, '<!-- gc:' . $serialized_block_name . ' ' );
}
}
return $has_block;
}
/** * Has block function which searches as well in reusable blocks. * * @param mixed $block_name Full Block type to look for. * @return bool */ function gcdocs_enhanced_has_block( $block_name ) { if ( has_block( $block_name ) ) { return true; } if ( has_block( 'core/block' ) ) { $content = get_post_field( 'post_content' ); $blocks = parse_blocks( $content ); return gcdocs_search_reusable_blocks_within_innerblocks( $blocks, $block_name ); } return false; } /** * Search for the selected block within inner blocks. * * The helper function for gcdocs_enhanced_has_block() function. * * @param array $blocks Blocks to loop through. * @param string $block_name Full Block type to look for. * @return bool */ function gcdocs_search_reusable_blocks_within_innerblocks( $blocks, $block_name ) { foreach ( $blocks as $block ) { if ( isset( $block['innerBlocks'] ) && ! empty( $block['innerBlocks'] ) ) { gcdocs_search_reusable_blocks_within_innerblocks( $block['innerBlocks'], $block_name ); } elseif ( 'core/block' === $block['blockName'] && ! empty( $block['attrs']['ref'] ) && has_block( $block_name, $block['attrs']['ref'] ) ) { return true; } } return false; }