Skip to content

3. Displaying custom blocks

Rob edited this page Mar 30, 2019 · 2 revisions

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 correct format to use is: block-{block slug}.php.

For example, if your block's slug is testimonial, Block Lab would look for a Block Template in your theme in this location: 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 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 slug}.php.

Example

A Block Template for a testimonial.

Template: my-custom-theme/blocks/preview-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.