wp_get_post_content_block_attributes()
云策文档标注
概述
wp_get_post_content_block_attributes() 函数用于从当前文章模板中检索 Post Content 块的属性数组。它仅在块主题环境下有效,并返回属性数组或 null。
关键要点
- 函数返回 Post Content 块的属性数组,若不存在则返回 null。
- 仅适用于块主题(通过 wp_is_block_theme() 检查),且需要有效的 $post_ID。
- 通过解析模板内容,使用 wp_get_first_block() 查找 'core/post-content' 块并提取其属性。
- 涉及模板 slug 的获取逻辑,包括处理默认模板(如 'singular'、'page'、'single')。
代码示例
function wp_get_post_content_block_attributes() {
global $post_ID;
$is_block_theme = wp_is_block_theme();
if ( ! $is_block_theme || ! $post_ID ) {
return null;
}
$template_slug = get_page_template_slug( $post_ID );
if ( ! $template_slug ) {
$post_slug = 'singular';
$page_slug = 'singular';
$template_types = get_block_templates();
foreach ( $template_types as $template_type ) {
if ( 'page' === $template_type->slug ) {
$page_slug = 'page';
}
if ( 'single' === $template_type->slug ) {
$post_slug = 'single';
}
}
$what_post_type = get_post_type( $post_ID );
switch ( $what_post_type ) {
case 'page':
$template_slug = $page_slug;
break;
default:
$template_slug = $post_slug;
break;
}
}
$current_template = get_block_templates( array( 'slug__in' => array( $template_slug ) ) );
if ( ! empty( $current_template ) ) {
$template_blocks = parse_blocks( $current_template[0]->content );
$post_content_block = wp_get_first_block( $template_blocks, 'core/post-content' );
if ( isset( $post_content_block['attrs'] ) ) {
return $post_content_block['attrs'];
}
}
return null;
}注意事项
- 函数在 WordPress 6.3.0 中引入,6.4.0 版本优化了无 Post Content 块时的返回值为 null。
- 依赖多个 WordPress 核心函数,如 wp_is_block_theme()、get_block_templates()、parse_blocks() 等,确保环境兼容性。
- 主要用于块编辑器设置(如 get_block_editor_settings()),开发者需在块主题上下文中调用。
原文内容
Retrieves Post Content block attributes from the current post template.
Source
function wp_get_post_content_block_attributes() {
global $post_ID;
$is_block_theme = wp_is_block_theme();
if ( ! $is_block_theme || ! $post_ID ) {
return null;
}
$template_slug = get_page_template_slug( $post_ID );
if ( ! $template_slug ) {
$post_slug = 'singular';
$page_slug = 'singular';
$template_types = get_block_templates();
foreach ( $template_types as $template_type ) {
if ( 'page' === $template_type->slug ) {
$page_slug = 'page';
}
if ( 'single' === $template_type->slug ) {
$post_slug = 'single';
}
}
$what_post_type = get_post_type( $post_ID );
switch ( $what_post_type ) {
case 'page':
$template_slug = $page_slug;
break;
default:
$template_slug = $post_slug;
break;
}
}
$current_template = get_block_templates( array( 'slug__in' => array( $template_slug ) ) );
if ( ! empty( $current_template ) ) {
$template_blocks = parse_blocks( $current_template[0]->content );
$post_content_block = wp_get_first_block( $template_blocks, 'core/post-content' );
if ( isset( $post_content_block['attrs'] ) ) {
return $post_content_block['attrs'];
}
}
return null;
}