函数文档

get_comment_delimited_block_content()

💡 云策文档标注

概述

get_comment_delimited_block_content() 函数用于返回包含注释分隔符的块内容,适用于 WordPress 块编辑器开发。它处理块名称、属性和内容,生成序列化的块输出。

关键要点

  • 函数返回包含注释分隔符的块内容字符串
  • 接受三个参数:块名称(可为 null)、块属性数组和块保存内容
  • 当块名称为 null 时(如 Classic 块),直接返回块内容
  • 使用 strip_core_block_namespace() 和 serialize_block_attributes() 辅助函数处理序列化
  • 空内容时生成自闭合块格式,非空时生成完整块格式

代码示例

function get_comment_delimited_block_content( $block_name, $block_attributes, $block_content ) {
    if ( is_null( $block_name ) ) {
        return $block_content;
    }

    $serialized_block_name = strip_core_block_namespace( $block_name );
    $serialized_attributes = empty( $block_attributes ) ? '' : serialize_block_attributes( $block_attributes ) . ' ';

    if ( empty( $block_content ) ) {
        return sprintf( '<!-- wp:%s %s/-->', $serialized_block_name, $serialized_attributes );
    }

    return sprintf(
        '<!-- wp:%s %s-->%s<!-- /wp:%s -->',
        $serialized_block_name,
        $serialized_attributes,
        $block_content,
        $serialized_block_name
    );
}

注意事项

  • 块名称参数可为 null,适用于未知块名的情况
  • 属性序列化使用 serialize_block_attributes(),确保格式正确
  • 输出格式遵循 WordPress 块注释标准,如

📄 原文内容

Returns the content of a block, including comment delimiters.

Parameters

$block_namestring|nullrequired
Block name. Null if the block name is unknown, e.g. Classic blocks have their name set to null.
$block_attributesarrayrequired
Block attributes.
$block_contentstringrequired
Block save content.

Return

string Comment-delimited block content.

Source

function get_comment_delimited_block_content( $block_name, $block_attributes, $block_content ) {
	if ( is_null( $block_name ) ) {
		return $block_content;
	}

	$serialized_block_name = strip_core_block_namespace( $block_name );
	$serialized_attributes = empty( $block_attributes ) ? '' : serialize_block_attributes( $block_attributes ) . ' ';

	if ( empty( $block_content ) ) {
		return sprintf( '<!-- wp:%s %s/-->', $serialized_block_name, $serialized_attributes );
	}

	return sprintf(
		'<!-- wp:%s %s-->%s<!-- /wp:%s -->',
		$serialized_block_name,
		$serialized_attributes,
		$block_content,
		$serialized_block_name
	);
}

Changelog

Version Description
5.3.1 Introduced.