admin管理员组

文章数量:1326038

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 badges
Add a comment  | 

1 Answer 1

Reset to default 0

Figured 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