[Plugin: WP-Blocks] Getting a random block by regex
-
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_
- The topic ‘[Plugin: WP-Blocks] Getting a random block by regex’ is closed to new replies.