Delete a Custom Field From Every Post (WP-CLI)
Adds a "wp delete-meta-key" command that removes one custom field key from all posts of a type, for example leftovers from an old SEO or page builder plugin, with a count before anything is deleted.
Opens WPIDE on
Code
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
return;
}
WP_CLI::add_command( 'delete-meta-key', function ( $args, $assoc_args ) {
global $wpdb;
$key = $args[0];
$post_type = sanitize_key( $assoc_args['post_type'] ?? 'any' );
$type_sql = 'any' === $post_type ? '' : $wpdb->prepare( ' AND p.post_type = %s', $post_type );
$count = (int) $wpdb->get_var( $wpdb->prepare(
"SELECT COUNT(*) FROM {$wpdb->postmeta} pm INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id WHERE pm.meta_key = %s" . $type_sql,
$key
) );
if ( ! $count ) {
WP_CLI::success( sprintf( 'No "%s" fields found.', $key ) );
return;
}
if ( empty( $assoc_args['yes'] ) ) {
WP_CLI::log( sprintf( '%d "%s" field rows would be deleted. Add --yes to delete them.', $count, $key ) );
return;
}
$post_ids = $wpdb->get_col( $wpdb->prepare(
"SELECT DISTINCT pm.post_id FROM {$wpdb->postmeta} pm INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id WHERE pm.meta_key = %s" . $type_sql,
$key
) );
foreach ( $post_ids as $post_id ) {
delete_post_meta( (int) $post_id, $key );
}
WP_CLI::success( sprintf( 'Deleted "%s" from %d posts.', $key, count( $post_ids ) ) );
}, array(
'shortdesc' => 'Deletes a custom field key from all posts.',
'synopsis' => array(
array( 'type' => 'positional', 'name' => 'key', 'description' => 'Exact meta key.' ),
array( 'type' => 'assoc', 'name' => 'post_type', 'optional' => true, 'default' => 'any' ),
array( 'type' => 'flag', 'name' => 'yes', 'optional' => true ),
),
) );
Notes
Example "wp delete-meta-key _old_plugin_data --post_type=page --yes"; back up the database first.
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.