Getting a random wp-block by regex

If you’re used to developing with a CMS such as CMS Made Simple, you would be quite used to having blocks of content separate from the main content system. These blocks can be re-used through-out existing content and within the theme templates.

One might even consider this a core function for a CMS. Sadly it’s missing from WordPress. Keir Whitaker has been working on this missing option and gives us wp-blocks.

It’s a great little plugin, though it currently has a couple of niggles:

  • Apostrophes are escaped in the output: ‘
  • One can’t call a block from inside content, it has to be from the theme template.

Despite this, I’m glad that he’s made the plugin available for public use.

Now, time to extend it!

As with global content blocks in CMS Made Simple, wp-blocks does not offer a way to fetch a random content block. I fixed this in CMS Made Simple by writing the Random Global Content Block plugin.

Now I’ve done something similar for wp-blocks:

Copy that code into your theme’s functions.php and then call from within your template with, as an example:

This will then fetch a wp-block with a name starting with testimonial_.

Leave a Reply

Your email address will not be published. Required fields are marked *