wordpress get term title on adding

I may have the terminology mixed up so I hope you can follow.

I have a custom post type of ‘Packages’
I have set the ability to create catagories called ‘Add Package Type’

Read More

When I add a category I wish to insert a new page with the title of the new category only when it is in the ‘Add Package Type’.

I cannot seem to get the category title with the following code, inside the $taxonomy I get ‘Add Package Type’ which is fine. But I wish to have the page as the same name as the title I have just entered.

Thanks

function custom_create_packages( $term_id, $tt_id, $taxonomy ){

    if($taxonomy == 'package type'){
        $new_page_title = $cat_title;
        $new_page_content = 'This is the page content';
        $new_page_template = ''; //ex. template-custom.php. Leave blank if you don't want a custom page template.
        //don't change the code bellow, unless you know what you're doing
        $page_check = get_page_by_title($new_page_title);
        $new_page = array(
            'post_type' => 'page',
            'post_title' => $new_page_title,
            'post_content' => $new_page_content,
            'post_status' => 'publish',
            'post_author' => 1,
        );
        if(!isset($page_check->ID)){
            $new_page_id = wp_insert_post($new_page);
            if(!empty($new_page_template)){
                update_post_meta($new_page_id, '_wp_page_template', $new_page_template);
            }
        }
    }
}

add_action( 'create_term', 'custom_create_packages', 10, 3 );

Related posts

Leave a Reply

1 comment

  1. If I’ve understood you correctly, you’ll have to retrieve the details of the term based on the $term_id parameter. Something like:

    function custom_create_packages( $term_id, $tt_id, $taxonomy ){
    
        if($taxonomy == 'package_type'){
            $term = get_term( $term_id, $taxonomy );
            $new_page_title = $term->name;
    

    I don’t know whether the taxonomy slug in your code (‘package type’) was just an example, but it should not contain spaces (see the Codex).

    It might be worth changing your action from create_term to create_{taxonomy} (e.g. create_package_type) to eliminate the need to check the taxonomy. Note that create_{taxonomy} only has 2 parameters ($term_id and $tt_id), since the taxonomy is known.

    I’m not certain, but it might be safer to call your function in the created_{taxonomy} hook (note the ‘d’), which is called after the clean_term_cache function is called (though given it’s a new entry, that probably won’t make a difference).