Displaying custom blocks

Luke Carbis edited this page Nov 12, 2018 · 1 revision

In order for blocks to properly display, you'll need to create an associated HTML template, using the Block Lab API to include field data. These templates are commonly referred to as Block Templates.

The Basics

The Block Template needs to be stored inside a blocks directory in your theme, using the slug of your block in the filename. The slug of your block can be seen in the Slug section of the Block editor. The correct format to use is: block-{block name}.php.

For example, if your block's slug is testimonial, Block Lab would look for the the Block Template file in your theme: blocks/block-testimonial.php. Block Lab first checks if the template exists in the child theme, and if not, in the parent theme.

Block Previews

Sometimes a block's template markup will be too detailed to be properly previewed in the WordPress editor. In this case, you may create a Preview Template. This will be used instead of the Block Template while previewing the block in the WordPress editor. Preview Templates should be saved in your theme, as block/preview-{block name}.php.

Example

A Block Template for a testimonial.

Template: my-custom-theme/blocks/testimonial.php

<img src="<?php block_field( 'profile-picture' ); ?>" alt="<?php block_field( 'author-name' ); ?>" />
<h3><?php block_field( 'author-name' ); ?></h3>
<p><?php block_field( 'testimonial' ); ?></p>

Overriding the template path

It is possible to change the template path so that it uses a custom template, outside of the theme or blocks directory.

To use a different template inside your theme, use the block_lab_override_theme_template( $theme_template ) filter. To use a different template outside your theme (for example, in a plugin), use the block_lab_template_path( $template_path ) filter.

Read more about using filters on WordPress.org.

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.