# List Custom Field Keys With Counts (WP-CLI)

> Adds a "wp meta-keys" command that lists every custom field key used by a post type and how many posts use it, which helps when cleaning up after old plugins or planning a migration.

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

## Code

```php
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
    return;
}

WP_CLI::add_command( 'meta-keys', function ( $args, $assoc_args ) {
    global $wpdb;

    $post_type = sanitize_key( $assoc_args['post_type'] ?? 'post' );
    $hidden    = ! empty( $assoc_args['hidden'] ) ? '' : "AND pm.meta_key NOT LIKE '\\_%'";

    $rows = $wpdb->get_results( $wpdb->prepare(
        "SELECT pm.meta_key, COUNT(DISTINCT pm.post_id) AS posts FROM {$wpdb->postmeta} pm
        INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
        WHERE p.post_type = %s $hidden GROUP BY pm.meta_key ORDER BY posts DESC, pm.meta_key",
        $post_type
    ), ARRAY_A );

    if ( ! $rows ) {
        WP_CLI::success( sprintf( 'No custom fields found for %s.', $post_type ) );
        return;
    }

    WP_CLI\Utils\format_items( $assoc_args['format'] ?? 'table', $rows, array( 'meta_key', 'posts' ) );
}, array(
    'shortdesc' => 'Lists custom field keys used by a post type.',
    'synopsis'  => array(
        array( 'type' => 'assoc', 'name' => 'post_type', 'optional' => true, 'default' => 'post' ),
        array( 'type' => 'flag', 'name' => 'hidden', 'optional' => true, 'description' => 'Include keys starting with an underscore.' ),
        array( 'type' => 'assoc', 'name' => 'format', 'optional' => true, 'default' => 'table', 'options' => array( 'table', 'csv', 'json' ) ),
    ),
) );
```

## Notes

Add --hidden to include keys that start with an underscore.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "List Custom Field Keys With Counts (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/
