WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

    $my_cat_id = wp_insert_category($my_cat);

    $my_cat_id = wp_create_category($cat_name,$cat_parent);


    $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
up vote 1 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


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.