# Remove Duplicate Post Meta Rows

> Run on demand to find custom field rows that are exact duplicates (same post, key and value) and keep only one of each, a common side effect of buggy imports and plugins.

- Type: PHP
- Runs: On demand
- Category: [Performance](https://wpide.com/library/category/performance/)
- Tags: database, metadata, cleanup
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/perf-duplicate-postmeta-cleanup/

## Code

```php
global $wpdb;

$wpide_deleted = (int) $wpdb->query(
    "DELETE m1 FROM {$wpdb->postmeta} m1
     INNER JOIN {$wpdb->postmeta} m2
        ON m1.post_id = m2.post_id AND m1.meta_key = m2.meta_key AND m1.meta_value = m2.meta_value AND m1.meta_id > m2.meta_id"
);

if ( $wpide_deleted ) {
    wp_cache_flush();
}

printf( 'Removed %d duplicate post meta row(s).', $wpide_deleted );
```

## Notes

Only exact duplicates are removed, keeping the oldest row; back up your database first.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Remove Duplicate Post Meta Rows" 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/
