WordPress.org

Ready to get started?Download WordPress

Forums

WP-Blocks
Getting a random block by regex (1 post)

  1. bigcalm
    Member
    Posted 3 years ago #

    This shouldn't be WP version specific.

    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]);
        }
      }

    This will allow you to get a single random block based upon a regex. For example:
    <?php get_wp_block_random('^testimonial_'); ?>
    Will return a block which has a name starting with testimonial_

    http://wordpress.org/extend/plugins/wp-blocks/

Topic Closed

This topic has been closed to new replies.

About this Plugin

About this Topic

  • RSS feed for this topic
  • Started 3 years ago by bigcalm
  • This topic is not a support question
  • WordPress version: 3.1

Tags