I have deep hierarchical taxonomy and I want to have all parent term assigned when I select a child term. I need it for category structure on a online listing/classified site.
CPT name: product
Taxonomy Name: product_cat
I have deep hierarchical taxonomy and I want to have all parent term assigned when I select a child term. I need it for category structure on a online listing/classified site.
CPT name: product
Taxonomy Name: product_cat
Hooking into save_post
action.
add_action('save_post', 'assign_parent_terms', 10, 2);
function assign_parent_terms($post_id, $post){
if($post->post_type != 'product')
return $post_id;
// get all assigned terms
$terms = wp_get_post_terms($post_id, 'product_cat' );
foreach($terms as $term){
while($term->parent != 0 && !has_term( $term->parent, 'product_cat', $post )){
// move upward until we get to 0 level terms
wp_set_post_terms($post_id, array($term->parent), 'product_cat', true);
$term = get_term($term->parent, 'product_cat');
}
}
}
While loop ensures we go upward until we hit top level terms.