3

I have the following core block HTML

<!-- wp:group -->
<div class="wp-block-group"><!-- wp:heading -->
<h2 id="hello-world">Hello world</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Lorem ipsum dolor...</p>
<!-- /wp:paragraph --></div>
<!-- /wp:group -->

Is it possible to create a custom block from PHP using that HTML? Similar to as I would create Patterns?

register_block_type() can be used to register blocks from PHP. Is it possible to simply pass the HTML to register_block_type() and create the custom block?

2 Answers 2

2

No, blocks are built with more than HTML - they need JS and PHP.

However, you could add an HTML block wherever you need it, then click the More Options dots in the block's toolbar, click Add to Reusable Blocks, name your block, and save it. That block will then be available to use wherever you want it, and if you edit it, that will apply the changes everywhere.

1

If you don't want it to show up in the editor, then it's definitely possible to create a dynamic block using only PHP and HTML. Here's a minimal example:

<?php

namespace Foo\Bar;

defined( 'WPINC' ) || die();

add_action( 'init', __NAMESPACE__ . '\register_blocks' );

function register_blocks(): void {
    register_block_type(
        'foo/php-only-block',
         array(
            'api_version' => 3,
            'render_callback' => __NAMESPACE__ . '\render_php_only_block',
        )
    );
}

function render_php_only_block( array $block_attributes, string $content ): string {
    return '<p>hello!</p>';
}

You can then add that to a theme template like this:

Block theme: <!-- wp:foo/php-only-block /-->

Classic theme: echo do_blocks( '<!-- wp:foo/php-only-block /-->' );

If you do want it to show up in the editor, then you'd need some minimal JS like you see in the Creating Dynamic Blocks tutorial.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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