Dynamically create/remove terms in taxonomy when custom post type is published/trashed

Am struggling a bit with creating & removing terms based on when a custom post type is published and trashed. Ideally, I would like to create a new term in my custom taxonomy when a custom post type is published. Then, when that post in the custom post type is trashed, I need to check and make sure that the count on that term is 0, and if so automatically delete the appropriate term. Here’s what I have thus far. The creation function is working correctly, but for I cannot figure out the trashed function. Your expertise is much appreciated!!

<?php
/**
  * Automatically creates terms in 'custom_taxonomy' when a new post is added to its 'custom_post_type'
  */
function add_cpt_term($post_ID) {
    $post = get_post($post_ID);

    if (!term_exists($post->post_name, 'custom_taxonomy'))
        wp_insert_term($post->post_title, 'custom_taxonomy', array('slug' => $post->post_name));
}
add_action('publish_{custom_post_type}', 'add_cpt_term');
?>

…and now for the function I’m having a hard time getting to work the way I want it to:

/**
  * Automatically removes term in 'custom_taxonomy' when the post of 'custom_post_type' is trashed
  */
function remove_cpt_term($post_ID) {
    $post = get_post($post_ID);
    $term = get_term_by('name', $post->post_name, 'custom_taxonomy', 'ARRAY_A');

    if ($post->post_type == 'custom_post_type' && $term['count'] == 0)
        wp_delete_term($term['term_id'], 'custom_taxonomy');
}
add_action('wp_trash_post', 'remove_cpt_term');
?>

Read more here:: Dynamically create/remove terms in taxonomy when custom post type is published/trashed

Leave a Reply

Your email address will not be published. Required fields are marked *