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.
Opens WPIDE on
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
- 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.