Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

share|improve this question
    
Just in case you did not see it, I've updated my answer to address an issue called out in the comments. –  MikeSchinkel Jan 31 '11 at 11:10

1 Answer 1

up vote 3 down vote accepted

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');
share|improve this answer
2  
You forgot to mention $append argument in your example, in current form every call will delete earlier tag. To add all three tags it needs to have $append or tags passed as array. There are also couple of simpler and more specific wrappers available - wp_set_post_tags() (same mechanics, just omits $taxonomy) and wp_add_post_tags() ($append set to true). –  Rarst Jan 31 '11 at 9:01
    
+1 for append - i remember it driving my nuts trying to figure it out –  Bainternet Jan 31 '11 at 10:02
    
@Rarst - Good catch. That's what I get when I try to answer too many questions in a weekend. I've updated the answer per your suggestions. PROPs to you and בניית אתרים too. –  MikeSchinkel Jan 31 '11 at 11:09
    
Thank you! I went with a slightly different solution: wp_set_post_tags( $created, $tags ); which sets them all at once. –  James Jan 31 '11 at 18:26
    
@James - Yes, with WordPress there are often several ways to accomplish the same goal. Glad I could point you in the right direction. –  MikeSchinkel Jan 31 '11 at 22:47

Your Answer

 
discard

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.