1

Hi There

Is there a way to include a Gutenberg Block in a PHP file?

Example:

I created a block named: posts grid, which is a block that displays the latest posts, the user could change the number of posts to display and the category to get posts from, now I want to create a custom post template and I want to use this block in it dynamically, what I am looking for is something that's similar to do_shortcode() for shortcodes

Thanks

  • My experience with Gutenberg is still relatively limited, so I won’t post this as an authoritative answer, but no, I really doubt you can. The output of a Gutenberg block is generated in JavaScript during the process of editing. So there is no PHP code that could be run to generate the same output. The only exception would be if a block was rendered server-side, then there might be a way. But it depends on the block, and the core blocks are not server rendered. – Jacob Peattie Feb 2 '19 at 0:55
1

You need to use Custom Post Type for blocks. What it does is you can register your own post template with predefined blocks in it. Which I believe is what you are looking for. Here's example of that -

function myplugin_register_book_post_type() {
    $args = array(
        'public' => true,
        'label'  => 'Books',
        'show_in_rest' => true,
        'template' => array(
            array( 'core/image', array(
                'align' => 'left',
            ) ),
            array( 'core/heading', array(
                'placeholder' => 'Add Author...',
            ) ),
            array( 'core/paragraph', array(
                'placeholder' => 'Add Description...',
            ) ),
        ),
    );
    register_post_type( 'book', $args );
}
add_action( 'init', 'myplugin_register_book_post_type' );

This function registers a CPT and via template option it specifying which block are inside of it. You can lock, loosely lock or allow other blocks to be inserted as well.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.