admin管理员组文章数量:1324904
By default the tag-cloud
block in the (Gutenberg) block-editor renders a root element as follows:
<p class="wp-block-tag-cloud">...</p>
This is the corresponding code what is renders the block: .php#L44
Filtering with pre_render_block
doesn't work.
Any idea how to filter this root element of this block?
By default the tag-cloud
block in the (Gutenberg) block-editor renders a root element as follows:
<p class="wp-block-tag-cloud">...</p>
This is the corresponding code what is renders the block: https://github/WordPress/WordPress/blob/master/wp-includes/blocks/tag-cloud.php#L44
Filtering with pre_render_block
doesn't work.
Any idea how to filter this root element of this block?
Share Improve this question asked Sep 8, 2020 at 13:08 luukvhoudtluukvhoudt 8411 gold badge8 silver badges19 bronze badges1 Answer
Reset to default 0Figured it out myself after all.
Instead of using the pre_render_block
filter, use the render_block
filter to do something like this:
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;
}
This should yield something like <div class="tags">...</div>
.
本文标签: Filter root element of tag cloud block
版权声明:本文标题:Filter root element of tag cloud block 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742129961a2422113.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论