Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm creating a batch uploader and it would be good if I could also add categories with parent categories to my posts.

I have the following code:

        $my_cat = array(
        'cat_name' => $cat_name,
        'category_description' => $cat_desc,
        'category_nicename' => $cat_slug,
        'category_parent' => $cat_parent);

if(function_exists('wp_insert_category')){
    $my_cat_id = wp_insert_category($my_cat);

}elseif(function_exists('wp_create_category')){
    $my_cat_id = wp_create_category($cat_name,$cat_parent);

}elseif(function_exists('wp_insert_term')){

    $parent_term = term_exists( $cat_name, $cat_parent );
    $parent_term_id = $parent_term['term_id'];
    $var = wp_insert_term($cat_name,$cat_parent);

    if ( is_wp_error($var) ){
    echo $var->get_error_message();
    echo " Category ";var_dump($cat_name);echo" failed to be created ";
    }

both $cat_name and $cat_parent are always valid with some value and $cat_parent exists always prior to creating $cat_name.

but always all I get is

Invalid taxonomy

which means that the last elseif runs.

i'm running this code from the theme's functions.php file

SO I have 2 questions:

first: why wont neither of the first two if cases run? (If i remove the if exists check, it reports that the function does not exist)

second: why the 3rd wont run?

share|improve this question

1 Answer 1

up vote 0 down vote accepted

wp_insert_category and wp_create_category are both in wp-admin/includes/taxonomy.php. They're not general use functions and can't be used just anywhere. wp_insert_term is, but you're using it incorrectly. See the Codex for details on proper usage, but in short, here's a cheat sheet:

wp_insert_term( $term, $taxonomy, $args = array() );
...
$defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');

I believe what you want to change your code to say is,

$var = wp_insert_term( $cat_name, 'category', array( 'parent' => $parent_term_id ) );
share|improve this answer
    
thank you for the quick and helpful response :) –  NorthPole Dec 4 '12 at 15:06
    
Absolutely, happy to help! –  Matthew Boynes Dec 4 '12 at 15:18

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.