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:

 * Gets a random block data by 'regex'
 * Requires
 * @param string $block_slug_regex 
 * @return string
 * @author Iain Cuthbertson
function get_wp_block_random($block_slug_regex) {
  global $wpdb;
  $block_slug_regex = trim($block_slug_regex);
  $data = (array)$wpdb->get_results("SELECT id FROM {$wpdb->prefix}wpb_content WHERE name REGEXP '{$block_slug_regex}' AND active = TRUE");  
  if (isset($data) && is_array($data) && count($data) > 0)
    $arrayIndex = array();
    foreach ($data as $row)
      $arrayIndex[] = $row->id;
    $randomIndex = mt_rand(0, count($arrayIndex) - 1);
    return get_wp_block_by_id($arrayIndex[$randomIndex]);

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 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.