# Remove Orphaned Term Relationships and Fix Term Counts

> Run on demand to delete category and tag links that point to posts that no longer exist, and then recount how many posts each term has.

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

## Code

```php
global $wpdb;

// Links between terms and posts that were deleted without cleaning up (links to link-manager objects are kept).
$wpide_removed = (int) $wpdb->query(
    "DELETE tr FROM {$wpdb->term_relationships} tr
     LEFT JOIN {$wpdb->posts} p ON p.ID = tr.object_id
     LEFT JOIN {$wpdb->links} l ON l.link_id = tr.object_id
     WHERE p.ID IS NULL AND l.link_id IS NULL"
);

$wpide_recounted = 0;
foreach ( get_taxonomies() as $wpide_tax ) {
    $wpide_terms = get_terms( array( 'taxonomy' => $wpide_tax, 'hide_empty' => false, 'fields' => 'tt_ids' ) );
    if ( ! is_wp_error( $wpide_terms ) && $wpide_terms ) {
        wp_update_term_count_now( $wpide_terms, $wpide_tax );
        $wpide_recounted += count( $wpide_terms );
    }
}

printf( 'Removed %d orphaned relationship(s) and recounted %d term(s).', $wpide_removed, $wpide_recounted );
```

## Notes

Run it from the snippet editor; on very large sites run it outside busy hours.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Remove Orphaned Term Relationships and Fix Term Counts" 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/
