首页 文章

使用Wordpress短代码功能渲染Gutenberg块,将属性作为参数发送

提问于
浏览
0

鉴于图库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块 . 您可以选择一个图库,它将保存 . 但是,我不想重复代码并在保存属性和PHP代码中使用html .

所以我想知道是否有办法使用相同的 rb_scroll_gallery_shortcode 函数来渲染前端的块 .

我已经看到你可以使用 register_block_type 并将 render_callback 设置为 rb_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',
) );

2 回答

  • 0

    您可以尝试将短代码转换为Gutenberg块,并在使用主题后,

    Registering the Dynamic Block Callback in 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

  • 0

    render_callback() 不是't getting any attributes (though it wasn' t),但是编辑器没有保存它们,因为我忘了从属性中删除一些测试数据 galleryID

    registerBlockType:

    save() 方法应该返回 null .

    该属性不应该有选择器数据,因为它用于在 save() 上查找标记返回值,在这种情况下返回 null . 我保存了.535180_ .

    attributes: {
        galleryID: {
            type: 'string',
            //This data should only be set if the value can be found in the markup return by save().
            //Since save() returns null, we let it out
            /*source: 'attribute',
            /*attribute: 'data-gallery-id',
            /*selector: '.rb-scroll-gallery-holder',*/
        },
    }
    

相关问题