0
votes

This code form another topic, auto create category after theme activation

function create_my_cat () {
        if (file_exists (ABSPATH.'/wp-admin/includes/taxonomy.php')) {
            require_once (ABSPATH.'/wp-admin/includes/taxonomy.php'); 
            if ( ! get_cat_ID( 'Testimonials' ) ) {
                wp_create_category( 'Testimonials' );
            }
        }
    }

add_action ( 'after_setup_theme', 'create_my_cat' );

I need code to add term automatic after theme activation, example i want to add term 'rock', 'pop', 'dance' to 'music' taxonomy after_theme_setup

2

2 Answers

0
votes

You can do that by wp_insert_category() function.

eg.

function create_my_cat () {
    if (file_exists (ABSPATH.'/wp-admin/includes/taxonomy.php')) {
        require_once (ABSPATH.'/wp-admin/includes/taxonomy.php'); 
        if ( ! get_cat_ID( 'Cat Name' ) ) {
            $wpdocs_cat = array('cat_name' => 'Cat Name', 'category_description' => 'A Cool Category', 'category_nicename' => 'category-slug', 'category_parent' => '', 'taxonomy' => 'music');
            $wpdocs_cat_id = wp_insert_category($wpdocs_cat);
            echo $wpdocs_cat_id;
        }
    }
}

add_action ( 'after_setup_theme', 'create_my_cat' );

you can define in which category you wants to add the terms/category, eg.

$cat_defaults = array(
    'cat_name' => 'Category Name',
    'category_description' => 'Description',
    'category_nicename' => 'slug', // Slug
    'category_parent' => '', // If parent 
    'taxonomy' => 'category' // In which taxonomy you wants to add this category
);
0
votes

using the wp_insert_term function allows us to programmatically create categories, tags, and other custom taxonomies.

function example_insert_category() {
    wp_insert_term(
        'Apple', // the term 
        'product', // the taxonomy
        array(
          'description' => 'A yummy apple.',
          'slug'        => 'apple'
        )
    );
}
add_action( 'after_setup_theme', 'example_insert_category' );