3

I'm using wp_insert_term to create categories, after the category is created I'd like to get its ID:

$cat_id = wp_insert_term($name, 'category', array('slug' => $slug) );

...however when I try to print $cat_id I get Array instead of the actual ID. I guess I have to state which part of the array I need, but I don't really know what the variable for the ID would be?

2 Answers 2

9

It should be a key of term_id, so echo out $cat_id['term_id'] and you should get the new terms ID.

4

According to the Codex:

Return Values (array|WP_Error)

The Term ID and Term Taxonomy ID.

Example:

array( 'term_id'=>12,'term_taxonomy_id'=>34)

So try for example:

$cid = wp_insert_term( $name, 'category', array( 'slug' => $slug ) );

if ( ! is_wp_error( $cid ) )
{
    // Get term_id, set default as 0 if not set
    $cat_id = isset( $cid['term_id'] ) ? $cid['term_id'] : 0;
    // ... etc ...
}
else
{
     // Trouble in Paradise:
     echo $cid->get_error_message();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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