您是否尝试过使用parse_blocks()
(传入get_the_content()
)? 返回内容中所有块的数组。从那里,可以使用数组映射或foreach提取块名称和id属性。
假设您只想从标题中提取锚定标记,可以执行以下操作:
$blocks = parse_blocks( get_the_content() );
$block_ids = array();
function get_block_id( $block ) {
if ( $block[\'blockName\'] !== \'core/heading\' ) return;
$block_html = $block[\'innerHTML\'];
$id_start = strpos( $block_html, \'id="\' ) + 4;
if ( $id_start === false ) return;
$id_end = strpos( $block_html, \'"\', $id_start );
$block_id = substr( $block_html, $id_start, $id_end - $id_start );
return $block_id;
}
foreach( $blocks as $block ) {
$block_id = get_block_id( $block );
if ( $block_id ) array_push ( $block_ids, $block_id );
}