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) {
if(
$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');
}
}
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) {
if(
$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');
}
}
Share
Improve this question
edited May 7, 2019 at 21:36
LoicTheAztec
3,39117 silver badges24 bronze badges
asked May 7, 2019 at 19:34
zEn feeLozEn feeLo
2073 silver badges18 bronze badges
1 Answer
Reset to default 1You 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 ) {
if(
$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 );
}
}
}