0

When a user clicks the Add New Category for my custom post type of Packages I wish to create a new page with the same name as the new category at the same time. I can create a new page through code but I cannot find the right hook for my function.php to run it.

What I need is a hook that will run for only the Packages post type.

Thanks

2

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

  • sorry just noticed as I was implementing this code is that actually I wish to add a page under the 'packages' custom post type when adding a category to it. Can I pass the post type the category is being added to and check that: if( 'packages' === $posttype){ – Keith Power Oct 3 '13 at 13:14
  • maybe the updated code will get you somewhat closer finding a solution? – birgire Oct 3 '13 at 22:54
0

I think using WordPress hook for custom taxonomy will be cleaner and faster.

do_action( "create_{$taxonomy}", int $term_id, int $tt_id )

As an example to fire a function when a new WooCommerce category gets created:

function custom_created_term( $term_id, $tt_id ) {
   // do stuff 
}
add_action('create_product_cat','custom_created_term');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.