Taxonomies are fantastic, but for some reason there is no built in method for forcing WordPress to select all parent terms of a taxonomy if a user only selects a child / grand-child term. We found a sweet method to force any selected taxonomy to also select all parent taxonomies as well. Thanks to the WordPress Stack Exchange user Sisir for this sweet function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
//http://wordpress.stackexchange.com/a/100708/57457 add_action( 'save_post', 'jb_force_form_cat_hierarchy', 10, 2 ); function kb_force_form_cat_hierarchy( $post_id, $post ) { $post_type = 'post-type'; // If this isn't a $post_type, don't update it. if($post->post_type != $post_type) return $post_id; $taxonomy = 'my-tax'; // get all assigned terms $terms = wp_get_post_terms($post_id, $taxonomy ); foreach($terms as $term){ while($term->parent != 0 && !has_term( $term->parent, $taxonomy, $post )){ // move upward until we get to 0 level terms wp_set_post_terms($post_id, array($term->parent), $taxonomy, true); $term = get_term($term->parent, $taxonomy); } } } |