0

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

1
  • Just in case you did not see it, I've updated my answer to address an issue called out in the comments. Commented Jan 31, 2011 at 11:10

1 Answer 1

3

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');
5
  • 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
    Commented Jan 31, 2011 at 9:01
  • +1 for append - i remember it driving my nuts trying to figure it out
    – Bainternet
    Commented Jan 31, 2011 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. Commented Jan 31, 2011 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
    Commented Jan 31, 2011 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. Commented Jan 31, 2011 at 22:47

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.