作为对@RiddleMeThis, 通过解析core/image
-阻止使用DOMDocument
:
In the init
-Hook, register your custom output function:
register_block_type( \'core/image\', [
\'render_callback\' => \'myImageOutput\'
] );
Define your custom output function:
在此函数中,渲染默认输出(
$content
) 作为第二个参数传递。可悲的是,第一个论点(是
$attributes
) 缺少必需的信息(附件ID和链接目的地除外)。
function myImageOutput( $attributes, $content ) {
// $content contains e.g.
// <!-- wp:image {"id":123,"linkDestination":"custom"} -->
// <figure class="wp-block-image"><a href="https://www.example.com"><img src="path/to/my/image.jpg" alt="Alternative text here" class="wp-image-123"/></a><figcaption>Caption goes here</figcaption></figure>
// <!-- /wp:image -->
// prepare array for all info. Note: alignment and customized
// size are ignored here since it was not required in this case
$info = [
\'title\' => \'\',
\'imagUrl\' => \'\',
\'blank\' => FALSE,
\'url\' => \'\',
\'caption\' => \'\',
];
// Fortunately, the attachment id is saved in $attributes, so
// we can get the image\'s url
$infos[ \'imageUrl\' ] = wp_get_attachment_image_src( $attributes[ \'id\' ], \'your-size\' )[ 0 ];
// we get the remaining info by loading the html via DOMDocument
libxml_use_internal_errors( TRUE );
$dom = new DOMDocument();
$dom->preserveWhiteSpace = FALSE;
$dom->loadHtml( mb_convert_encoding( $content, \'HTML-ENTITIES\', \'UTF-8\' ) );
// get the figure element
$figure = $dom->getElementsByTagName( \'figure\' )[ 0 ];
// alternatively, get the image title or description etc.
// by querying it from the database
$infos[ \'title\' ] = $figure->getElementsByTagName( \'img\' )[ 0 ]->getAttribute( \'alt\' );
// if we have a custom url on the image
if ( isset( $attributes[ \'linkDestination\' ] ) && $attributes[ \'linkDestination\' ] == \'custom\' ) {
$a = $figure->getElementsByTagName( \'a\' )[ 0 ];
$infos[ \'url\' ] = $a->getAttribute( \'href\' );
$infos[ \'blank\' ] = strpos( $infos[ \'url\' ], get_home_url() ) !== 0;
}
// caption, also see https://stackoverflow.com/a/2087136/1107529
// because the caption can contain html
$figCaption = $figure->getElementsByTagName( \'figcaption\' );
if ( count( $figCaption ) ) {
$caption = \'\';
foreach ( $figCaption[ 0 ]->childNodes as $child ) {
$caption .= $dom->saveHTML( $child );
}
$infos[ \'caption\' ] = $caption;
}
// create your custom html output here. In my case, I passed the
// info to a vue component
$html = sprintf( \'<my-custom-vue-component :info="%s"></my-custom-vue-component>\',
esc_attr( json_encode( $info ) ) );
return $html;
}
这个解决方案对我很有用。我相信,总有一天会有更好的方法来做到这一点,可能是在古腾堡生态系统变得更加成熟的时候。但就目前而言,它的工作没有问题。
希望这有帮助。