Automatically calling custom functions in GenerateBlocks

I write lots of custom functions that return different data and information. For example manipulating the output of ACF fields.

GenerateBlocks has lots and lots of hooks, which allows us to do this. However one thing that I found annoying was that I had to create a really long switch statement for each and every custom function that I created. This made it very difficult to keep track of all my functions.

I create a little snippet that can be added to your website that automatically calls your custom function directly from the dynamic data section.

php
<?php /* * @function Automatically call custom functions in Generateblocks Dynamic Data * @author Taylor Drayson * @since 22/09/2022 * * Replace $key with your unique prefix for all custom functions */ add_filter( 'generateblocks_dynamic_content_output', function( $content, $attributes ) { if ( 'post-meta' === $attributes['dynamicContentType'] && isset( $attributes['metaFieldName'] ) ) { $key = 'tct'; // Replace with your unique key $match = preg_match('#^'. $key .'(.*)$#i', $attributes['metaFieldName']); if($match){ return call_user_func($attributes['metaFieldName']); }else{ switch($attributes['metaFieldName']){ case 'my-custom-function': return 'hello world'; // Replace with function } } } return $content; }, 10, 2 );

How to use

1. Copy and paste the snippet

You can put the code into functions.php or your favourite code snippet plugin. Make sure you replace line 14 with your unique key. This is important, as this is your function identifier.

Copy and paste the snippet

2. Add your custom function

I added a simple greeting function that returns Hello Taylor, however this could be whatever you want.

Make sure your function is prefixed with your unique key that you chose.

Add your custom function

3. Insert a block from GenerateBlocks that supports dynamic data

Insert a block from GenerateBlocks that supports dynamic data

4. Add dynamic data

In the block sidebar, under Dynamic Data, select Post Meta as the content source.

In the Post meta field, add your custom function name that you created.

Add dynamic data

5. Final result

Once you have done that, you should see your custom function rendered on the frontend.

Final result

Now this is only a simple example, there are lots of things you can do with this approach, including using and manipulating WordPress functions, ACF fields, taxonomies, post types and more.

👋🏻 Weekly Tutorial Digest

I send out a weekly newsletter with links to new tutorials written in the last week, you can subscribe below.

🔒I won't send you spam, I promise