Set post categories to include parents when setting child category

This will check to see if there is a hierarchy and set all parent categories as checked. This function assumes that if there’s multiple categories already set, then don’t do the function, since the categories would be correct if multiples are set.

function set_product_parent_categories( $post_id ) {
    $category = wp_get_post_terms( $post_id, 'product_cat' );
    // If multiple categories are set. Bail Out
    if (count ($category) > 1 ) return;

    $terms = array($category[0]->term_id);
    if ($category[0]->parent > 0){
        $parent = $category[0]->parent;
        while ($parent > 0){
            // Make an array of all term ids up to the parent.
            $terms[] = $parent;
            $grandpa = get_term($parent, 'product_cat');
            $parent = $grandpa->parent;
        }
    }
    // If multiple terms are returned, update the object terms
    if (count($terms) > 1) wp_set_object_terms( $post_id, $terms, 'product_cat' );
}
add_action( 'woocommerce_update_product', 'set_product_parent_categories', 10, 1 );