1
votes

I need help How can I create taxonomy to custom post type after theme activation? example case: I have custom post type 'book' and custom taxonomy 'genre' for my custom post type. This is easy way when add code to functions.php, but i need to auto create horor, comedy, fiction to 'genre' when theme activation (after_theme_setup)

Very interest with this topic Creating Wordpress Category at the time of Theme Activation

1

1 Answers

0
votes

Here is the code to automatically add terms to existing custom taxonomy.

Assumption:: I've assumed that the post type 'book' is already registered and the custom taxonomy 'genre' is also already registered.

<?php
    add_action( 'after_setup_theme', 'wpso2523951_add_taxonomy_genre' );
    function wpso2523951_add_taxonomy_genre(){
        $custom_post_type = 'book';
        $custom_taxonomy = 'genre';
        $required_terms = [ 'horror'=>'Horror',
                            'comedy'=>'Comedy',
                            'fiction'=>'Fiction',
                        ];
        if( post_type_exists( $custom_post_type ) && taxonomy_exists( $custom_taxonomy ) ){
                register_taxonomy_for_object_type( $custom_taxonomy, $custom_post_type);
                foreach($required_terms as $slug=>$term_name){
                    wp_insert_term(
                              $term_name, 
                              $custom_taxonomy,
                              [
                                'description'=> $term_name.' genre.',
                                'slug' => $slug,
                              ]
                            );
                    }

            }
        }
?>