Creating WordPress Category at the time of Theme Activation

I am going to create a function that will check whether if a Category named Testimonials is already available or not. If it is available do noting, whereas if it is not there, then create a new Category named Testimonials. I am using following code but nothing happened at the time of theme activation. What is missing?

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 ('create_category', 'create_my_cat');

Related posts

Leave a Reply

2 comments

  1. The action create_category runs when a new category is created.

    You want your category creation function to run when the theme is activated. The relevant action is after_setup_theme.

    Drop this in your theme’s functions.php and you should be good to go:

    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' );
    
  2. Note: If you have already used a function my_theme_name_setup() {} you don’t need another function. One more *note to mention; you can also use category_exists instead of get_cat_ID(), so the full code example is:

    function my_theme_name_setup() {
    
        if( file_exists( ABSPATH . '/wp-admin/includes/taxonomy.php' ) ) :
            require_once( ABSPATH . '/wp-admin/includes/taxonomy.php' );
    
                if( ! category_exists( 'name' ) ) :
    
                    wp_create_category( 'name' );
    
                endif;// Category exists
    
        endif;// File exists 
    
    }
    add_action( 'after_setup_theme', 'my_theme_name_setup' );