I am using wp_set_object_terms to add terms (attributes) to our WooCommerce products:

wp_set_object_terms($id, array($migrate_case), 'pa_case');

This gives us the advantage (instead of using wp_set_post_terms) that non-existing terms are created automatically.

Is there any way to get wp_set_object_terms() to tell me if it had to create a new term?

Thanks in advance for any help.

  • Did you look at this line in the source code: core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/…. It is passed an array of old taxonomy term ids, so I assume you could compare with count(), maybe.
    – Hans
    Commented Oct 3, 2018 at 20:40
  • @Michael - looks promising: do_action( 'set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids ); return $tt_ids; How do I get wp_set_object_terms($id, array($migrate_dial), 'pa_dial'); to return the $old_tt_ids? Commented Oct 4, 2018 at 17:46
  • You can't, but you can add a filter to the mentioned hook right before your function call to wp_set_object_terms, and remove it right afterwards. At least that's what I usually do in similar situations. add_action remove_action.
    – Hans
    Commented Oct 4, 2018 at 18:58

1 Answer 1


You can add a filter for a specific function call like so:

add_filter( 'set_object_terms', 'checkNewTerm', 10, 6 );

function checkNewTerm( $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids ) {

    // Do stuff, ie. compare count of $tt_ids and $old_tt_ids

wp_set_object_terms($id, array($migrate_case), 'pa_case');

remove_filter( 'set_object_terms', 'checkNewTerm', 10, 6 );

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.