Answer the question
In order to leave comments, you need to log in
How to auto select parent category if child category is selected?
Good day
There is a list of taxonomies of such a structure
category 1 - subcategory 1 - subcategory
2
-subcategory
3
How to auto-select category 1 if selected, for example, subcategory 3
I want to do without plugins if possible
Answer the question
In order to leave comments, you need to log in
found a solution
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');
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question