开发者

Wordpress > Create category as child of "uncategorized" (catid=1)

开发者 https://www.devze.com 2023-01-10 07:32 出处:网络
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,开发者_StackOverflow it creates them...

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,开发者_StackOverflow 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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消