I have a form which makes people decide about the sub-categories of their product and the form gets submitted on user post method

Im trying to add the parent category to it as well

Now I tested couple of way to adding the $term but each time it just get replaced not added

add_action('transition_post_status', 'new_product_add', 10, 3);
function new_product_add($new_status, $old_status, $post) {
        $old_status != 'publish' 
        && $new_status == 'pending' 
        && !empty($post->ID) 
        && in_array( $post->post_type, 
            array( 'product') 
        ) {
            $term = get_term_by('name', 'parent_category', 'product_cat');
            wp_set_object_terms($post->ID, $term->term_id, 'product_cat');

1 Answer 1


You just need to add a missing boolean argument in wp_set_object_terms() function like:

wp_set_object_terms($post->ID, $term->term_id, 'product_cat', true);

This time the term will be appended and not replaced.

You should check that the term doesn't exist yet on the product, before appending it like:

add_action( 'transition_post_status', 'new_product_add', 10, 3 );
function new_product_add( $new_status, $old_status, $post ) {
        $old_status !== 'publish' 
        && $new_status === 'pending' 
        && ! empty($post->ID) 
        && $post->post_type === 'product'
    ) {
        $taxonomy = 'product_cat';
        $term_id  = get_term_by( 'name', 'parent_category', $taxonomy )->term_id;

        if( ! has_term( $term_id, $taxonomy ) ) {
            wp_set_object_terms( $post->ID, $term_id, $taxonomy );

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.