Quick Script to Count Block Usage

Here’s a quick script to determine what blocks a site is using and how often they use them:

<?php

require_once __DIR__ . '/wp-load.php';

$sql = 'select * from wp_posts where post_content like "%<!-- wp:%"';

$results = $wpdb->get_results($sql);
$blocks = [];

// Loop through each post and get a list of all blocks used in gutenberg post_content
foreach ($results as $post) {
    $matches = [];
    preg_match_all('/<!-- wp:(.*?) -->/', $post->post_content, $matches);
    if ( !empty($matches) ) {
        $block_names = $matches[1];

        foreach ( $block_names as $block_name ) {
            $name = explode(' ', $block_name);
            $name = $name[0] ?? $block_name;

            if ( !isset($blocks[$name]) ) {
                $blocks[$name] = 0;
            }
            ++$blocks[$name];
        }
    }
}

print_r($blocks);

Comments

Leave a Reply

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