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