Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save trey8611/7826c3180b1cca8828ba6492d0e9bd22 to your computer and use it in GitHub Desktop.
Save trey8611/7826c3180b1cca8828ba6492d0e9bd22 to your computer and use it in GitHub Desktop.
[Delete empty taxonomy terms on post delete] #wpallimport
// Delete empty taxonomies on post delete
function wpai_remove_taxonomies_on_delete( $post_id, $import ) {
    $taxonomy = 'product_cat'; // change this to the taxonomy name
    $terms = wp_get_object_terms( $post_id, $taxonomy );

    if ( ! empty( $terms ) ) {
        $all_terms = array();
        foreach ( $terms as $term ) {
            if ( $term->count < 2 ) {
                $all_terms[] = $term->term_id;
            }
        }
        if ( ! empty( $all_terms ) ) {
            foreach ( $all_terms as $term_id ) {
                wp_delete_term( $term_id, $taxonomy );
            }
        }
    }
}
add_action( 'pmxi_before_delete_post', 'wpai_remove_taxonomies_on_delete', 10, 2 );
@renzocastillo
Copy link

Thanks my friend! It worked perfectly !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment