Adding Categories Through Function

admin2025-06-03  4

I am creating a template theme for WP and am wondering if there is a way of the theme adding new categories to the db, through the functions.php upon activation of the theme.

It seems like a fairly straight forward thing to do, and can quite easily be done to post formats.

Of course its simple enough to tell the end users what categories they'll need to add once the have activated the theme, but I was wondering if that could be a step we could just miss out.

Anyways, thanks for your help, and give me a slap if there is an obvious answer :)

Matt

I am creating a template theme for WP and am wondering if there is a way of the theme adding new categories to the db, through the functions.php upon activation of the theme.

It seems like a fairly straight forward thing to do, and can quite easily be done to post formats.

Of course its simple enough to tell the end users what categories they'll need to add once the have activated the theme, but I was wondering if that could be a step we could just miss out.

Anyways, thanks for your help, and give me a slap if there is an obvious answer :)

Matt

Share Improve this question edited Feb 9, 2019 at 0:00 fuxia 107k39 gold badges255 silver badges461 bronze badges asked May 16, 2013 at 17:36 MattEarlyComMattEarlyCom 112 bronze badges 3
  • You are talking about the activation of both a theme and a plugin. What is the relationship? – s_ha_dum Commented May 16, 2013 at 17:59
  • I assumed plugin was a typo and he meant theme, maybe not though. – Andrew Bartel Commented May 16, 2013 at 18:02
  • apologies, yeah, it was a typo... what a numpty :P – MattEarlyCom Commented May 16, 2013 at 20:05
Add a comment  | 

1 Answer 1

Reset to default 1

Themes do not have an equivalent of register_activation_hook() like plugins.

You may also run into issues during a review if you're hoping to be hosted on the repo. I'm not sure how creating categories classifies exactly, but doing things like creating post types is explicitly disallowed.

That said, you can use wp_create_category() in your functions.php file with a check to see if the category exists with term_exists(). Code below is untested.

if(!term_exists('my_category_name','category')) {
    wp_create_category('my_category_name');
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748928199a314895.html

最新回复(0)