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');
?>

Related posts

1 comment

  1. Ok, I think I’ve figured out a viable solution. Kinda disappointed that there’s no way I’ve found thus far to hook directly into trash_{custom_post_type} like I was able to on the publish_{custom_post_type} hook. Here’s a solution for anyone else struggling with this issue. If anyone has any better suggestions, please feel free to share!

    /**
      * 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('slug', $post->post_name, 'custom_taxonomy');
    
        // target only our custom post type && if no posts are assigned to the term
        if ('custom_post_type' == $post->post_type && $term->count == 0)
            wp_delete_term($term->term_id, 'custom_taxonomy');
    }
    add_action('wp_trash_post', 'remove_cpt_term');
    

Comments are closed.