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

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

## Code

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

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Delete a Custom Field From Every Post (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/
