默认情况下,(Gutenberg)块编辑器中的tag-cloud块呈现根元素,如下所示:
...这是相应的代码,用于呈现块:https://github.com/WordPress/WordPress/blob/master/wp-includes/blocks/tag-cloud.php#L44
使用pre_render_block进行过滤不起作用。
知道如何过滤这个块的根元素吗?
发布于 2020-09-09 07:52:40
毕竟是我自己想出来的。
与其使用pre_render_block过滤器,不如使用render_block过滤器来执行如下操作:
add_filter('render_block', function($html, $block) {
if ($block['blockName'] !== 'core/tag-cloud') {
return $html;
}
$doc = new \DOMDocument($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$ps = iterator_to_array($doc->getElementsByTagName('p'));
$p = empty($ps) ? new \DOMElement('p') : current($ps);
return replaceChild($doc, $p, 'div', ['class' => 'tags'])->saveHTML();
}, 10, 2);
function replaceChild(\DOMDocument $doc, \DOMElement $target, string $tag, array $attrs = []) {
$replacement = $doc->createElement($tag);
if (!empty($attrs)) {
foreach ($attrs as $key => $value) {
$replacement->setAttribute($key, $value);
}
}
if ($target->hasChildNodes()) {
$children = iterator_to_array($target->childNodes);
foreach ($children as $child) {
$replacement->appendChild($child);
}
}
$target->parentNode->replaceChild($replacement, $target);
return $doc;
}这应该会产生类似于
...
的东西。
https://wordpress.stackexchange.com/questions/374490
复制相似问题