<?php
add_action('init', 'alt_type', 0);
function alt_type()
{
// Add new taxonomy, make it hierarchical like categories
//first do the translations part for GUI
    $labels = array(
        'name' => __('Tipo'),
        'singular_name' => __('Tipo'),
        'search_items' => __('Buscar Tipos'),
        'all_items' => __('Todos Tipos'),
        'parent_item' => __('Hierarquia Tipo'),
        'parent_item_colon' => __('Parent Tipos:'),
        'edit_item' => __('Editar Tipo'),
        'update_item' => __('Atualizar Tipo'),
        'add_new_item' => __('Adicionar Tipo'),
        'new_item_name' => __('Adicionar nome do tipo'),
        'menu_name' => __('Tipos de veículo'),
    );
// Now register the taxonomy
    register_taxonomy('tipo',
        array('product', 'veiculos'),
        array(
            'hierarchical' => true,
            'labels' => $labels,
            'show_ui' => true,
            'show_in_rest'=>true,
            'show_admin_column' => true,
            'query_var' => true,
            'rewrite' => array('slug' => 'tipo'),
        ));
}


add_filter( 'woocommerce_rest_prepare_product', 'custom_products_api_data', 90, 2 );
function custom_products_api_data( $response, $post ) {

    // retrieve a custom field and add it to API response
    $response->data['tipo'] = wp_get_post_terms( $post->ID, 'tipo', [] );
    return $response;

}

//REST
add_action( 'rest_api_init', 'get_taxonomies_custom_veiculos_tipo' );

function get_taxonomies_custom_veiculos_tipo() {

    // register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
    register_rest_field( 'product', 'tipo', array(
            'get_callback'    => 'get_tipo_do_veiculo',
            'update_callback' => 'update_tipo_veiculo',
            'schema'          => null,
        )
    );
}
function update_tipo_veiculo($value, $object, $field_name){

    $term = $value;
    $taxonomy = 'tipo';
    $parent_term = term_exists( $term, 'tipo' ); // array is returned if taxonomy is given
    //Manually creating the taxonomy term
    wp_insert_term($term, $taxonomy);
    //Manually assigning the term
    wp_set_object_terms($object->id, $term, $taxonomy);
    return update_post_meta($object->id, $field_name, $value);


}
function get_tipo_do_veiculo( $object ) {
    $post_id = $object['id'];
    return get_the_terms($post_id, 'tipo');
}