create blocks programmtically on theme activation

I have got my theme set to where on activation pages are created and templates are set, how can I add gutenberg blocks?

UPDATE:

Doesn’t create page and if I comment out the page_block_template function and make ‘post_content’ a empty string ' ' then it will create the page. So How do you do this, add blocks to a page template?

Function to add blocks to the page.

function page_block_template() {
    $pages_type_object = get_post_type_object( 'page' );
    $pages_type_object->template = array( 
        array( 'core/heading', array( 
            'level'         =>  '3',
            'className'     =>  'header',
            'content'       =>  ''
         ) ),
        array( 'core/separator', array( 
            'className' =>  'is-style-wide'
        ) ),
        array( 'core/paragraph', array( 
            'className' =>  'margin',
        ) ),

        array( 'core/list', array( 
            'className' =>  'list-unstyled h5',
            // STYLE <li class="list-inline-item"> ??

        ) ),

        array( 'core/heading', array( 
            'level'         =>  '3',
            'className'     =>  'header',
            'content'       =>  ''
         ) ),
        array( 'core/separator', array( 
            'className' =>  'is-style-wide'
        ) ),
     );
     $pages_type_object->template_lock = 'all';
}
add_action( 'init', 'page_block_template' );

Creates the page

if (isset($_GET['activated']) && is_admin()) {
    $page_title="Page";
    $page_content = page_block_template();
    $page_check = get_page_by_title($page_title);
    $page = array( 
        'post_type'     =>  'page',
        'post_title'    =>  $page_title,
        'post_content'  =>  $page_content,
        'post_status'   =>  'publish',
        'post_author'   =>  $user_id,
        'post_slug'     =>  'page'
    );
    if(!isset($page_check->ID) && !the_slug_exists('page')) {
        $page_id = wp_insert_post($page);
    }
}

1 Answer
1

You can’t use block templates this way. They are used only by Gutenberg on client side (JavaScript) when new post content is created. In your case you are creating page on server side (PHP). However you can create pages with initial block structure. Create new page manually and save it without adding any content (there will be only empty block structure as defined by your block template). Then get it’s post_content value either from database using some DB client, or read and print it in some temporary PHP function. But you must get value exactly as stored in database. Use this text as string value for post_content in your page creation code.

This way you will have new page created with initial content matching your block template. Don’t forget to change value if you change template structure.

Leave a Comment