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