Creating tags via API

I’m working on using the WP API to insert posts via AJAX.

What’s the proper way of adding tags dynamically to a custom post type? These tags would not be predefined, but rather be created on demand by the user.

Currently I’m doing this:

            $tags = explode(" ", $_POST['post_tags']);

        $new_entry = array(
            'post_title' => $_POST['post_title'],
            'post_content' => $_POST['post_content'],
            'post_status' => 'publish',
            'post_author' => $current_user->ID,
            'post_type' => 'customposttype',
            'post_tags' => $tags);

        $created = wp_insert_post( $new_entry );

(Yes, this is prototype code and I’m not sanitizing input yet :))

Solutions Collecting From Web of "Creating tags via API"

Hi @James:

If you have the post ID of your newly created post (the $created variable from your question) you use the wp_set_object_terms() function, for example:

wp_add_post_tags($created,'My First Tag');
wp_add_post_tags($created,'My Second Tag');
wp_add_post_tags($created,'My Third Tag');