Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.