delete terms wich contain zero post when removing terms from a post


when removing terms from a post, delete terms which contain zero post. when updating a post, delete terms which contain zero post.

i have tried the code bellow, but it doesn't work..

add_filter('wp_remove_object_terms','delete_unused_terms');
function delete_unused_terms($term_ids, $taxonomy) {
    foreach ( $term_ids as $term_id ) {
        $term = get_term($term_id, $taxonomy);
        $term_count = $term->count;
        if ($term_count<1) {
            wp_delete_term($term_id, $taxonomy);
        }
    }
}
- - Source

Answers

answered 1 week ago sftt #1

Unfortunately, there is no wp_remove_object_terms filter.

But there is an action deleted_term_relationships;

Please, try to use

add_action( 'deleted_term_relationships', 'yuor_prefix_update_delete_term_if_empty', 10, 3 );

function yuor_prefix_update_delete_term_if_empty( $object_id, $term_ids, $taxonomy ) {
    wp_update_term_count( $term_ids, $taxonomy );

    foreach ( $term_ids as $term_id ) {
        $term = get_term($term_id, $taxonomy);
        $term_count = $term->count;

        if ($term_count<1) {
            wp_delete_term($term_id, $taxonomy);
        }
    }
}

comments powered by Disqus