Home / Admin / Dynamic Shortcode Execution
Duplicate Snippet

Embed Snippet on Your Site

Dynamic Shortcode Execution

Dynamic shortcode execution with block editor support.
Allows shortcodes to execute everywhere, even within paragraph blocks.

Code Preview
php
<?php
<?php
/**
 * Enable live preview of all shortcodes in the block editor (Gutenberg / Site Editor).
 */
if ( ! defined( 'ABSPATH' ) ) exit;
// === Front-end: Ensure shortcodes work normally ===
add_filter( 'widget_text', 'do_shortcode' );
add_filter( 'the_content', 'do_shortcode' );
add_filter( 'render_block', function( $block_content, $block ) {
    return do_shortcode( $block_content );
}, 10, 2 );
// === Editor: Live preview for shortcodes in Gutenberg / Site Editor ===
add_action( 'enqueue_block_editor_assets', function() {
    wp_add_inline_script(
        'wp-blocks',
        "
        (function(){
            wp.data.subscribe(function(){
                const blocks = wp.data.select('core/block-editor').getBlocks();
                blocks.forEach(block => {
                    if (!block.attributes || !block.attributes.content) return;
                    const content = block.attributes.content;
                    if (content.includes('[')) { // naive check for shortcode
                        // Fetch rendered shortcode via REST
                        wp.apiRequest({
                            path: '/wp/v2/blocks/preview',
                            method: 'POST',
                            data: { content: content }
                        }).then(function(response){
                            // Find the block in the editor and replace its preview HTML
                            const el = document.querySelector('[data-block="'+ block.clientId +'"]');
                            if(el) el.innerHTML = response;
                        });
                    }
                });
            });
        })();
        "
    );
});

Comments

Add a Comment