Include a Gutenberg Block in a PHP file

admin2025-06-03  5

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

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

Share Improve this question asked Feb 1, 2019 at 22:56 Douara AbderrahmanDouara Abderrahman 411 silver badge6 bronze badges 1
  • 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 Commented Feb 2, 2019 at 0:55
Add a comment  | 

1 Answer 1

Reset to default 2

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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748951164a315094.html

最新回复(0)