首页 > 解决方案 > 使用 Wordpress 简码函数呈现 Gutenberg 块,将属性作为参数发送

问题描述

给定画廊 ID,我有一个生成画廊的简码。

function rb_scroll_gallery_shortcode( $atts, $content ) {
    $a = shortcode_atts( array(
        'id' => -1,
    ), $atts );
    $gallery_ID = $a['id'];

    $output = '';
    if($gallery_ID != -1){
        ob_start();
        $gallery = new RB_Scroll_Gallery($gallery_ID);
        $gallery->render();
        $output = ob_get_clean();
    }
    return $output;
}
add_shortcode( 'rb_scroll_gallery', 'rb_scroll_gallery_shortcode' );

现在,我制作了一个在编辑器中完美运行的 Gutenberg 块。您可以选择一个画廊,它将保存。但是,我不想重复代码并将 html 放在 save 属性和 php 代码中。

所以我想知道是否有一种方法可以使用相同rb_scroll_gallery_shortcode的函数在前端渲染块。

我已经看到您可以使用register_block_type并将其设置render_callbackrb_scroll_gallery_shortcode,但我需要在块中选择的 ID 将其发送到$atts数组中的函数

//This uses the shortcode funtion, but doesn't gives the gallery ID
register_block_type( 'cgb/block-rb-scroll-gallery-block', array(
    'render_callback' => 'rb_scroll_gallery_shortcode',
) );

标签: wordpresswordpress-gutenberggutenberg-blocks

解决方案


您可以尝试将简码转换为古腾堡块并在您的主题中使用后,

在 PHP 中注册动态块回调

/**
 * Register the GitHub Gist shortcode
 */
function gggb_init() {
        add_shortcode( 'github-gist', 'gggb_render_shortcode' );
        register_block_type( 'github-gist-gutenberg-block/github-gist', array(
                'render_callback' => 'gggb_render_shortcode',
        ) );
}
add_action( 'init', 'gggb_init' );

When your block is rendered on the frontend, it will be processed by your render callback:

function gggb_render_shortcode( $atts ) {
        if ( empty( $atts['url'] )
                || 'gist.github.com' !== parse_url( $atts['url'], PHP_URL_HOST ) ) {
                return '';
        }
        return sprintf(
                '<script src="%s"></script>',
                esc_url( rtrim( $atts['url'], '/' ) . '.js' )
        );
}

**Note:** this render callback is intentionally different than the Gutenberg block’s edit callback. Our preference is to use GitHub’s provided JavaScript embed code because this lets GitHub change the embed’s behavior at a future date without requiring a developer to make changes.

请参阅链接以获取更多信息,https://pantheon.io/blog/how-convert-shortcode-gutenberg-block


推荐阅读