views:

38

answers:

2

I've got a script in my functions.php file that checks for the existence of several categories that are required by my theme, and if they are not present, it creates them...

if(!get_cat_ID('my-category')){wp_create_category('my-category');}

I need to modify this script in two ways...

First, I need to create the category so that its parent category is the "Uncategorized" category (or id 1).

Second, if the category already exists, but its parent is not id 1, I need to make it so.

A: 

First, test if category exists. If it does, use get_category_parents() to get the parents of an existing category.

$parentID = get_category_parents(my-category-ID, false);

Second, the second accepted argument of wp_create_category() is the category you wish to assign as the parent category.

if(!get_cat_ID('my-category')){wp_create_category('my-category',parent category ID);}

Third, if the category does exist, you can use wp_update_term() to change it's attributes.

wp_update_term( $term_id, $taxonomy, $args );
kevtrout
Thanks kevtrout. I believe I'm getting close with your help. I just don't want to have to do this test every time someone hits a page on the site. I'd like to wrap this in my functions.php in a way that it only runs once when the theme is first activated. Any ideas for that? If so, what would your solution stub out to look like?
Scott B
A: 

To answer the question asked in your comment on my previous answer...How to run the category modification function when a user activates your theme?

You'll want to use an action hook. Specifically, 'switch_theme'. This is the codex page for all action hooks, I can't link to switch_theme specifically, but scroll down and you'll find it. There is no specific information on this hook, but usage is simple. You can include your function in functions.php or in a plugin file, and after the function definition, include this hook:

function add_my_categories($my-theme-name){
        //if $my-theme-name == 'my_theme_name
            //test if category exists
            //if exists, update
            //if doesn't exist, create and assign parent
    }
add_action('switch_theme','add_my_categories');

the 'add_action()' call will run the named function when the named hook is encountered in wordpress. The 'switch_theme' hook runs after a theme is changed.

It's important to know that this hook will provide the name of the new current theme to your function, which can accept it as an argument if you need it. For instance, to make sure the function only runs if your theme is the one activated. I suppose if this function is in your theme's functions.php file, it will NEVER run unless your theme is activated, so you can determine if you need to double check the theme name.

kevtrout
Perfect. Thanks Kevtrout
Scott B