The ContentBlock class may look a bit scary at first, but don’t worry, it’s more friendly than it looks. I will try to explain its most important elements, to help you quickly understand how to use it.
For starters, take a look at the $theme_blocks_locations association table. Here we declare each layout and provide a path to the file responsible for describing it. As we can see, the selected file has access to the full scope of the layout.
The display_theme_blocks method checks if the given block exists, and then uses get_theme_part to refer to the file with the given layout’s code. The get_theme_part function is not available in WordPress by default. It is a helper created by our company, which allows us to build pages from code divided into smaller blocks. Note that WordPress has a similar built-in function, which you may use as a replacement, called get_template_part. You can find its declaration at the end of this post.
Each new layout that we want to add to the project is declared in $theme_blocks_locations using the following syntax:
‘layouts_name’ => ‘path_to_file’
The last step is to specify where in the code we want to display our flexible content field:
<?php ContentBlock::display_theme_blocks(); ?>
Exemplary use in a project
This is what the contents of the parts folder look like. Notice the block folder, where the flexible content files are situated. To refer to the file visible on the screen, you would need to use: get_theme_part(‘block/accordion/accordion-item’) or get_template_part(‘parts/block/accordion/accordion-item.php’).
Code visible in the screenshot