Add a Block Lab Block to Your Website Content

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 in a file in the 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: {theme directory}/blocks/block-testimonial.php. Block Lab first checks if the template exists in the child theme, and if not, then in the parent theme.

Block templates are expected to load in the following order:

  1. blocks/{name}/preview.php (if in the editor)
  2. blocks/preview-{name}.php (if in the editor)
  3. blocks/preview.php (if in the editor)
  4. blocks/{name}/block.php
  5. blocks/block-{name}.php
  6. blocks/block.php

Block Theme Folder Structure

Support for structuring blocks inside directories like so:

  • /theme
    • /blocks
      • /block_one
        • preview.php
        • block.php
        • block.css
      • /block_two
        • preview.php
        • block.php
        • block.css

Note: It does NOT auto-enqueue JavaScript files.

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 {theme directory}/block/preview-{block slug}.php.

Example

A block template for a testimonial would be saved in the template file 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.