How can I create WordPress tags programmatically?

The following snippet adds WordPress categories programmatically. My question is how do you add tags programmatically?

//Define the category
$my_cat = array('cat_name' => 'My Category', 'category_description' => 'A Cool Category', 'category_nicename' => 'category-slug', 'category_parent' => '');

// Create the category
$my_cat_id = wp_insert_category($my_cat);

In this question, I’m talking about adding the tags into database programmatically.

Read More

Say, I got 1000 tags to add to a fresh installation. And I don’t want to go through the regular admin panel to add tags one by one manually. I’m looking for a programmatic solution. The snippet I posted takes care of the add of cats… thanks to the specific wp function wp_insert_category…. there is no function called wp_insert_tag though…

However, looking at the codex, I see the wp_insert_term function which may very well be the one to do the job – it seems.

Related posts

Leave a Reply

1 comment

  1. Use wp_insert_term() to add categories, tags and other taxonomies, because wp_insert_category() fires a PHP error “Undefined function”.

    <?php wp_insert_term( $term, $taxonomy, $args = array() ); ?> 
    

    $term is the term to add or update.

    Change the value of $taxonomy into post_tag if it’s a tag and category if it’s a category.

    In $args array, you can specify values of inserted term (tag, category etc.)

    Example:

    wp_insert_term(
      'Apple', // the term 
      'product', // the taxonomy
      array(
        'description'=> 'A yummy apple.',
        'slug' => 'apple',
        'parent'=> $parent_term['term_id']  // get numeric term id
      )
    );