Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

Code

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 add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.