I'm currently trying to assign a custom taxonomy to a WooCommerce product via the REST API. I created this custom taxonomy named "editoriales" using JetEngine and have activated the "Is Hierachical" and "Show in REST API" options.
When I create a new product via POST, I'm trying to assign the taxonomy as follows:
{
...
"editoriales": [1055],
...
}
Where 1055
is the term_id
of the taxonomy I want to assign to the product. However, this is not working - the product is created, but without the "editoriales" taxonomy assigned to it.
Furthermore, when I try to update an existing product via PUT and assign the "editoriales" taxonomy, it still doesn't work:
{
"product": {
"editoriales": [1055]
}
}
Also tried with this code in the functions.php
file, but got Error 500.
// Registro de la API para la taxonomía personalizada "editoriales"
add_action( 'rest_api_init', 'register_rest_field_for_custom_taxonomy_editoriales' );
function register_rest_field_for_custom_taxonomy_editoriales() {
register_rest_field('product', "editoriales", array(
'get_callback' => 'product_get_callback',
'update_callback' => 'product_update_callback',
'schema' => null,
));
}
// Obtener los registros de la taxonomía en la REST API de WooCommerce
function product_get_callback($post, $attr, $request, $object_type) {
$terms = array();
// Obtener los términos
foreach (wp_get_post_terms($post['id'], 'editoriales') as $term) {
$terms[] = array(
'term_id' => $term->term_id,
'name' => $term->name,
'slug' => $term->slug
);
}
return $terms;
}
// Actualizar los registros de la taxonomía en la REST API de WooCommerce
function product_update_callback($values, $post, $attr, $request, $object_type) {
// ID del producto
$postId = $post->get_id();
// Ejemplo: $values = [1055];
// Asignar los términos
wp_set_object_terms($postId, $values, 'editoriales');
}
I made a GET request to a product that already has the "editoriales" taxonomy assigned, and I can see the taxonomy data in the response, with term_id as the identifier.
Has anyone else encountered this problem before? Any ideas why I can't assign my custom taxonomy to the product when I create or update it via the WooCommerce REST API? Any help or guidance would be appreciated.