Skip to content

Instantly share code, notes, and snippets.

@tdmrhn
Forked from hughc/gutenberg-audit.php
Created February 23, 2023 04:44
Show Gist options
  • Save tdmrhn/07dccb0362325eeaf8310b0a29be5c8b to your computer and use it in GitHub Desktop.
Save tdmrhn/07dccb0362325eeaf8310b0a29be5c8b to your computer and use it in GitHub Desktop.
Gutenberg Audit for WordPress
<?php
/*
Plugin Name: Gutenberg Audit
Plugin URI: http://highbrow.com.au/plugins/gutenberg-audit
description: What blocks is your site using?
Version: 0.1
Author: Hugh Campbell
Author URI: http://highbrow.com.au/
License: GPL2
*/
function my_admin_menu()
{
add_management_page(
'Gutenberg audit',
'Gutenberg audit',
'manage_options',
'gutenberg_audit',
'gutenberg_audit_contents',
'dashicons-schedule',
3
);
}
add_action('admin_menu', 'my_admin_menu');
function gutenberg_audit_contents()
{
?>
<h1>
<?php esc_html_e('List of all blocks in use.', 'my-plugin-textdomain'); ?>
</h1>
<?php
$args = array(
'sort_order' => 'asc',
'sort_column' => 'post_title',
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'meta_key' => '',
'meta_value' => '',
'authors' => '',
'child_of' => 0,
'parent' => -1,
'exclude_tree' => '',
'number' => '',
'offset' => 0,
'post_type' => 'page',
'post_status' => 'publish'
);
$pages = get_pages($args); // get all pages based on supplied args
$tally = [];
$pageBreakdown = [];
$recurseFunc = function ($page, $block) use (&$tally, &$pageBreakdown, &$recurseFunc) {
$blockName = $block['blockName'];
// echo "$blockName<br>";
if (array_key_exists($blockName, $tally)) {
$tally[$blockName]++;
} else {
$tally[$blockName] = 1;
}
if (!array_key_exists($page->post_title, $pageBreakdown)) {
$pageBreakdown[$page->page_title] = [];
}
$pageList = &$pageBreakdown[$page->post_title];
if (array_key_exists($blockName, $pageList)) {
$pageList[$blockName]++;
} else {
$pageList[$blockName] = 1;
}
// print_r($tally);
$inner = $block['innerBlocks'];
foreach ($inner as $innerBlock) {
$recurseFunc($page, $innerBlock);
}
};
foreach ($pages as $page) { // $pages is array of object
$blocks = parse_blocks($page->post_content);
foreach ($blocks as $block) {
$recurseFunc($page, $block);
}
}
?>
<h2>
Block Breakdown
</h2>
<ul>
<?php
foreach ($tally as $blocktype => $value) {
echo sprintf('<li>%s - %s</li>', $blocktype, $value);
}
?>
</ul>
<h2>
Page Breakdown
</h2>
<?php
foreach ($pageBreakdown as $page_title => $pageTally) {
?>
<h2>
<?= $page_title ?>
</h2>
<ul>
<?php
foreach ($pageTally as $blocktype => $value) {
echo sprintf('<li>%s - %s</li>', $blocktype, $value);
}
?>
</ul>
<?php
}
// echo wp_sprintf('tally %s', print_r($tally, true));
// echo wp_sprintf('pageList %s', print_r($pageBreakdown, true));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment