Front End Post Save Child terms

With saving child terms, I believe you can add them to the $term_array group where the parent lives. From the perspective of a post (or custom post type) saving the taxonomy has nothing to do with parent or child.

The WP Codex states “For hierarchical terms (such as categories), you must always pass the id rather than the term name to avoid confusion where there may be another child with the same name.” This implies that you should be able to pass the child ID and it will be categorized in the child term.

Source: https://codex.wordpress.org/Function_Reference/wp_set_post_terms#Notes

Regarding displaying the children, you can do it one of two ways. The first, you can continue looping through children based on your code:

/*
Display child terms:

Source:
get_term_children()
*/ $parent_terms = wp_get_post_terms(get_the_ID(), 'city-type'); if ( ! empty( $parent_terms ) && ! is_wp_error( $parent_terms ) ){ foreach ( $parent_terms as $parent ) { echo '' . $parent->name . ''; $children = get_term_children($parent->ID, 'city-type'); //term_id, taxonomy if(!empty($children) && ! is_wp_error( $children )){ foreach($children as $child){ echo '' . $child->name . ''; } } } }

Or you can loop through children after getting them from the parent (in the case that you may have a parent but need it’s children:

/* OR YOU CAN GET CHILDREN DIRECTLY */
$children = get_terms(array(
    'parent' => 10 //ID_OF_PARENT_YOU_WANT
));

if(!empty($children) && ! is_wp_error( $children )){
    foreach($children as $child){
        echo '' . $child->name . '';
    }
}

EDIT: Showing an example save function.

wp_set_object_terms($pid, $nhb_type_value, 'city-type');

update_post_meta($pid, 'imic_property_custom_city', $property_custom_city);
$city_for_update = get_term_by('slug', $city_type_value, 'city-type');
$term_array = array();
while ($city_for_update->parent != 0) {
    $city_for_update = get_term_by('id', $city_for_update->parent, 'city-type');
    array_push($term_array, $city_for_update->slug);
}
array_push($term_array, $city_type_value);

/*Find child ID the user selected*/
while ($child_term->parent != 0) {
    $child_term = get_term_by('id', $child_term->ID, 'city-type');
    //Get child term object and add to term_array
    array_push($term_array, $child_term->slug);
}

wp_set_object_terms($pid, $term_array, 'city-type');

Leave a Comment