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?


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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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