• I need my gutenberg wordpress dynamic block to render all paragraph blocks in the page (just for display, and not in database).

    <?php
    function create_block_init()
    {
        register_block_type(__DIR__ . '/build',
            array(
                'render_callback' => 'render_my_widget'
            ));
    
    }
    
    function replaceTextInParagraphs($newValToSet)
    {
        $post = get_post();
        $content = $post->post_content;
        if (has_blocks($content)) {
            $blocks = parse_blocks($content);
            for ($i = 0; $i <= count($blocks); $i++) {
                $block = $blocks[$i];
                if ($block['blockName'] === "core/paragraph") {
                    if (!empty($block['innerHTML'])) {
                        $block['innerHTML'] = str_replace("foo", $newValToSet, $block['innerHTML']);
                    }
                    if (!empty($block['innerContent']) && is_array($block['innerContent'])) {
                        $block['innerContent'] = array_map(function ($item) use ($newValToSet) {
                            return str_replace("foo", $newValToSet, $item['innerHTML']);
                        }, $block['innerContent']);
                    }
                }
            }
        }
        return $content;
    
    }
    
    function render_my_widget($attributes, $content)
    {
        $newValToSet = $attributes['newVal'];
        $newContent = replaceTextInParagraphs($newValToSet);
        // How do i re render the content of the post???
    }

    I want basically replace some text in the paragraphs based on the current widget attribute. I am new to wordpress and not sure that what i am doing is the best option to achieve it. Also the example is simplified version. I need this block to be dynamic (it relies on URL passed params). The question is how to re-write the paragraphs after i replaced the text? Hope it make sense. thanks.

    • This topic was modified 1 year, 9 months ago by alex257.
Viewing 1 replies (of 1 total)
  • Hi @alex257,

    I might be able to help as I’ve done something similar, but so I can do so effectively, I would like to know:

    What should the editor display when you’re editing the post? Would it show a placeholder which would then be replaced by the actual value, or should it show the actual value?

    Also, you say:

    based on the current widget attribute

    Could you clarify what you mean by widget attribute? Is this an attribute of the block? I’m asking because you also mentioned:

    it relies on URL passed params

    So I assume it relies on both a block attribute and the URL query params?

Viewing 1 replies (of 1 total)
  • The topic ‘How to re-render static block from a dynamic block without saving it in the data’ is closed to new replies.