An easy way to display dynamic data in WordPress blocks

blockify Avatar

·

·

In this tutorial, we will go over how to create and use custom template tags in WordPress blocks. Template tags are a simple way to insert dynamic content into your blocks, such as post data or other options stored in the database. We will be using the render_block filter to replace these tags with the corresponding data.

Enabling custom template tags

First, we need to create a function that will handle the replacement of the template tags with the corresponding data. In this function, we will use regular expressions to search for strings between curly braces, such as { post_name }.

Next, we will use the render_block filter to call this function whenever a block is being rendered on the front-end. This filter allows us to modify the HTML output of a block before it is displayed to the user.

Copied!
// Use preg_replace() to search for and replace template tags function replace_template_tags( $block_content, $block ) { $block_content = preg_replace( '/{ post_name }/', get_the_title(), $block_content ); return $block_content; } add_filter( 'render_block', 'replace_template_tags', 10, 2 );Code language: PHP (php)

Using Custom Template Tags

Once you have created your custom template tag function, you can start using it in your blocks. To do this, simply include the template tag within curly braces, such as { post_name } anywhere custom text is supported:

When the block is rendered on the front-end, the template tag will be replaced with the corresponding data.

Copied!
<h1>{ post_name }</h1>Code language: HTML, XML (xml)

Additional Examples

Custom template tags can be used for any option stored in the database, not just post meta. For example, you can use them to insert the current date, the site title, or the number of comments on a post.
Here’s an example of how to create a custom template tag for the number of comments on a post:

Copied!
function replace_template_tags( $block_content, $block ) { $block_content = preg_replace( '/{ post_name }/', get_the_title(), $block_content ); $block_content = preg_replace( '/{ comment_count }/', get_comments_number(), $block_content ); return $block_content; } add_filter( 'render_block', 'replace_template_tags', 10, 2 );Code language: PHP (php)

Conclusion

Custom template tags are a powerful way to add dynamic content to your WordPress blocks. With just a few lines of code, you can create tags that can be used to insert post data, site options, or any other information stored in the database. This can be a great way to add more flexibility and customization to your blocks.