Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to echo gutenberg block programatically?

I'm curious why this never asked before.

With shortcode its very easy if we want to echo the shortcode programatically for example like this:

echo do_shortcode('[best_selling_products]');

How to do the same with gutenberg block? Is there any similar function like:

echo do_block('woocommerce/product-best-sellers');
like image 779
gidiwe2427 Avatar asked Feb 04 '26 22:02

gidiwe2427


1 Answers

Yes, you are very close, the equivalent function is do_blocks() with an s, eg:

echo do_blocks('<!-- wp:woocommerce/product-best-sellers {...} /-->');

In the example above, you would also need to set any required attributes such as the category. Render WooCommerce Block 'Product Filter – Attributes'... is a more detailed example for WooCommerce.

Any serialized block content string generated by the Editor or yourself can be used in PHP template with do_blocks(), eg a posts featured image:

do_blocks('<!-- wp:post-featured-image {"isLink":true,"align":"wide", "size:"thumbnail"} /-->'); 

Inside {...} are the blocks attributes. If the block has default attributes, they are used if you don't provide them or you can selectively set your own.

like image 98
S.Walsh Avatar answered Feb 08 '26 21:02

S.Walsh