Render WooCommerce Block ‘Product Filter – Attributes’ in code rather than via backend

WooCommerce provides the Gutenberg block “Product Filter – Attributes”, which you can add to the sidebar or footer widgets or basically everywhere, where you can add Gutenberg blocks.

However, I need to render this block in the overwritten woocommerce template “archive-product.php” in a very specific location.

Does anyone know, how it’s possible to render Gutenberg blocks purely in code?

And then I still need to tell the block, which attribute(s) it should provide filters for. In backend, you simply can pick the global woocommerce attributes to filter by. I need to do all of that in code.

Thank you, have a nice day


Block content (including woocommerce blocks) can be rendered in a template via the do_blocks() function.

The easiest way to generate the block code is to create a new post/page, insert the block you want, configure the attributes/settings as needed, then switch from the Visual editor to the Code editor (shortcut: Ctrl+Shift+Alt+M) to get the code required.

Here is an example of the attribute filter block for “your-attribute” for inserting in a template file:

    echo do_blocks('<!-- wp:woocommerce/attribute-filter {"attributeId":1,"heading":"Filter by your-attribute"} -->
        <div class="wp-block-woocommerce-attribute-filter is-loading" data-attribute-id="1" data-show-counts="true" data-query-type="or" data-heading="Filter by your-attribute" data-heading-level="3"><span aria-hidden="true" class="wc-block-product-attribute-filter__placeholder"></span></div>
        <!-- /wp:woocommerce/attribute-filter -->'

NB. For the block to render correctly, the woocommerce or custom JS and CSS needs to be enqueued too..

Source: stackoverflow