Find Posts Using a Block (WP-CLI)
Adds a "wp find-block" command that lists the content using a given block, such as core/table or a plugin's block, with how many times it appears in each post.
Opens WPIDE on
Code
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
return;
}
WP_CLI::add_command( 'find-block', function ( $args, $assoc_args ) {
global $wpdb;
$name = strtolower( trim( $args[0] ) );
if ( false === strpos( $name, '/' ) ) {
$name = 'core/' . $name;
}
// Core blocks are stored without the "core/" namespace in the block comment.
$stored = 0 === strpos( $name, 'core/' ) ? substr( $name, 5 ) : $name;
$rows = $wpdb->get_results( $wpdb->prepare(
"SELECT ID, post_title, post_type, post_status, post_content FROM {$wpdb->posts}
WHERE post_status NOT IN ('trash','auto-draft','inherit') AND post_type NOT IN ('revision','customize_changeset')
AND post_content LIKE %s ORDER BY ID",
'%<!-- wp:' . $wpdb->esc_like( $stored ) . '%'
) );
$items = array();
foreach ( $rows as $row ) {
$count = preg_match_all( '/<!--\s+wp:' . preg_quote( $stored, '/' ) . '[\s\/]/', $row->post_content );
if ( ! $count ) {
continue;
}
$items[] = array(
'ID' => $row->ID,
'type' => $row->post_type,
'status' => $row->post_status,
'uses' => $count,
'title' => $row->post_title,
);
}
if ( ! $items ) {
WP_CLI::success( sprintf( 'No content uses %s.', $name ) );
return;
}
WP_CLI\Utils\format_items( $assoc_args['format'] ?? 'table', $items, array( 'ID', 'type', 'status', 'uses', 'title' ) );
}, array(
'shortdesc' => 'Lists content that contains a block.',
'synopsis' => array(
array( 'type' => 'positional', 'name' => 'block', 'description' => 'Block name, for example core/table.' ),
array( 'type' => 'assoc', 'name' => 'format', 'optional' => true, 'default' => 'table', 'options' => array( 'table', 'csv', 'json', 'count' ) ),
),
) );
Notes
Pass the full block name, for example "wp find-block core/image" or "wp find-block acme/slider --format=csv".
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.