views:

62

answers:

1

My goal is just to use some type of default method for checking if category exist in Wordpress, and if it doesn't, add the category. Same with tags.

Here is a mess I made trying to make it happen:

<?php if ( is_term( 'football' , 'category' ) ){

}

else (

$new_cat = array('cat_name' => 'Football', 'category_description' => 'Football Blogs', 'category_nicename' => 'category-slug', 'category_parent' => 'sports');

$my_cat_id = wp_insert_category($new_cat); )

I plan to add this as a plugin. Any thoughts or help would be great!

+1  A: 

You can just run;

wp_insert_term('football', 'category', array(
    'description' => 'Football Blogs',
    'slug' => 'category-slug',
    'parent' => 4 // must be the ID, not name
));

The function won't add the term if it already exists for that taxonomy!

Out of interest, when will you be calling this kind of code in your plugin? Make sure you register it within an activation hook function, otherwise it'll run on every load!

UPDATE

To get the ID of a term by slug, use;

$term_ID = 0;
if ($term = get_term_by('slug', 'term_slug_name', 'taxonomy'))
    $term_ID = $term->term_id;

Replace 'taxonomy' with the taxonomy of the term - in your case, 'category'.

TheDeadMedic
Man, is there a possibility of using the slug for parent? Or turning the code around that use the slug attribute? Because I would have to manually set up the code to assume the ID and insert the parent terms in the beginning (instead of just knowing the slug name).
No probs - check the updated answer :)
TheDeadMedic