# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Developer](https://wpide.com/library/category/developer/)
- Tags: wp-cli, blocks, audit
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/cli-find-block-usage/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Find Posts Using a Block (WP-CLI)" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
