0

I have a form on my site that allows signed in users tag products from the front-end of the site in a basic form. I am using Woocommerce as the commerce platform.

Woocommerce uses Custom Post Types to register its products. Product tags is a taxonomy (product_tag) Woocommerce uses for tagging products.

I am using wp_set_object_terms to insert the terms the users submit. Problem is when they submit new "tags" it overwrites any existing "Tags" and replaces with their new ones.

I just need a way for the form to add their tags and keep the existing tags of the product (post).

here is what I have:

if (is_user_logged_in()) {


    if(isset($_POST['submitted']) && isset($_POST['post_nonce_field']) && wp_verify_nonce($_POST['post_nonce_field'], 'post_nonce')) {


    //Tagging
    wp_set_object_terms( $post->ID, explode( ',', $_POST['postTags'] ), 'product_tag' );

}

?>
<form name="primaryTagForm" action="#" id="primaryTagForm" method="POST" enctype="multipart/form-data" >
    <fieldset class="tags">
        <label for="post_tags">Tags:</label>
        <input type="text" value="" tabindex="35" name="postTags" id="postTags" />
    </fieldset>

    <fieldset>
        <input type="hidden" name="submitted" id="submitted" value="true" />
        <?php wp_nonce_field( 'post_nonce', 'post_nonce_field' ); ?>
        <button class="button" type="submit"><?php _e('Tag Product', 'framework') ?></button>
    </fieldset>
</form>

1 Answer 1

3

The fourth parameter to wp_set_object_terms() is an "append" argument.

$append (bool) (required) If true, tags will be appended to the object. If false, tags will replace existing tags

    Default: False

http://codex.wordpress.org/Function_Reference/wp_set_object_terms

Your code should work if you pass true as that fourth argument.

wp_set_object_terms( 
  $post->ID, 
  explode( ',', $_POST['postTags'] ), 
  'product_tag',
  true
);
2
  • Boom. That's even better than getting the current terms and merging with the posted terms. Commented Feb 23, 2014 at 22:30
  • lol wow, it was right there in the codex if I looked for it. Thanks for pointing that one out!
    – Derek
    Commented Feb 23, 2014 at 22:45

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.