Search code examples
wordpresswordpress-gutenberggutenberg-blocks

Use Wordpress shortcode function to render Gutenberg block, sending the attributes as parameters


I have a shortcode that generates a gallery, given the gallery 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' );

Now, I've made a Gutenberg block that works perfectly in the editor. You can select a gallery and it will save. However, I dont want to repeat code and have the html in the save property and in the php code.

So I was wondering if there is a way to use that same rb_scroll_gallery_shortcode function to render the block in the front end.

I've seen that you can use register_block_type and set the render_callback to rb_scroll_gallery_shortcode, but I need the ID selected in the block to send it to the function in the $atts array

//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',
) );

Solution

  • I've found out the little thing that messed up my code. The problem wasn't that the render_callback() wasn't getting any attributes (though it wasn't), but it was that the editor wasn't saving them because I forgot to remove some testing data from the attribute galleryID

    In the registerBlockType:

    The save() method should return null.

    The attribute should not have a selector data, since it is used to find the value on the markup return by the save(), wich in this case returns null. I've forgot to remove this data, thats why the attribute wasn't being saved.

    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',*/
        },
    }