古腾堡编辑器获取第一张图片区块

在使用 get_children 函数获取文章图片的时候出现了一个问题,那就是使用古腾堡编辑器书写的文章中无法获取到图片,为了获取古腾堡编辑器编辑的文章的图片,必须要进行区块解析,下面的函数可以获取到古腾堡编辑器编辑的文章的图片,并返回第一张图片区块的图片id;

Gutenberg Editor
古腾堡编辑器
/**
 * 获取基于古腾堡编辑区块的第一张图片的id
 *
 * @author 智慧宫
 * @link   https://lerm.net
 */
protected function first_image_in_blocks() {
	$post   = get_post( $this->args['post_id'] );
	$blocks = parse_blocks( $post->post_content );

	// Get all blocks that have a core/image blockName
	$images = array_filter(
		$blocks,
		function( $block ) {
			return 'core/image' === $block['blockName'];
		}
	);
	// If there are any images, get the id from the first image, otherwise
	$first_image_blocks = array_shift( $images );
	if ( null !== $first_image_blocks ) {
		return $first_image_blocks['attrs']['id'];
	}
}

发表评论

游客欢迎您123