Hook onto Add New Category

You can try out the created_term hook:

/**
 * Do 'stuff' when a term is created in the 'country' taxonomy 
 * using info from the referred page
 *
 * @param integer $term_id
 * @param integer $tt_id
 * @param string $taxonomy
 * @return void
 */
function custom_created_term( $term_id, $tt_id, $taxonomy )
{
    $my_cpt="packages";  // Edit this to your needs
    $my_tax = 'category';  // Edit this to your needs

    if( DOING_AJAX && $my_tax === $taxonomy )
    {
        // Try to get the post type from the post id in the referred page url 
        // Example: /wp-admin/post.php?post=2122&action=edit&message=1

        parse_str( parse_url( wp_get_referer(), PHP_URL_QUERY ) , $params );

        if( isset( $params['post'] ) )
        {
            $post_id = intval( $params['post'] );
            if( $post_id > 0 && $my_cpt === get_post_type( $post_id ) )
            {
                // do stuff ... 

            }
        }           
    }   
}

The ajax request is sent to admin-ajax.php when you use “+ Add New category” to create a new category in the edit post screen. The form data sent in this ajax request, doesn’t seems to contain any explicit information on the current post object. Therefore I use the referred page info as a last resort.

There might be other better ways to do this, but I’m not sure how 😉

Leave a Comment