Add custom taxonomy term in woocommerce REST API

Viewed 2240

I have created custom taxonomy "Brands" and attached to woocommerce products. Unfortunately, It is not available in woocommerce REST API response. How to attach custom taxonomy term to woocommerce rest API. Currently there is no documentation about attachment of custom taxonomy. Is there any hook or filter ?

4 Answers

I solved by using this code.You will be able to GET and Update custom taxonomy by using this method. Basically. You can add this code in functions.php file or in plugin.

Step:1 Replace brands with your taxonomy_name.

Step:2 If your taxonomy have custom fields, replace custom_field_name with yours.

Taxonomy Code:

add_action( 'init', 'create_brands_hierarchical_taxonomy', 0 );

//create a custom taxonomy name it topics for your posts
 
function create_brands_hierarchical_taxonomy() {
 
// Add new taxonomy, make it hierarchical like categories
//first do the translations part for GUI
 
  $labels = array(
    'name' => _x( 'Brands', 'taxonomy general name' ),
    'singular_name' => _x( 'Brand', 'taxonomy singular name' ),
    'search_items' =>  __( 'Search Brands' ),
    'all_items' => __( 'All Brands' ),
    'parent_item' => __( 'Parent Brand' ),
    'parent_item_colon' => __( 'Parent Brand:' ),
    'edit_item' => __( 'Edit Brand' ), 
    'update_item' => __( 'Update Brand' ),
    'add_new_item' => __( 'Add New Brand' ),
    'new_item_name' => __( 'New Brand Name' ),
    'menu_name' => __( 'Brands' ),
  );    
  
    $capabilities = array(
        'manage_terms'               => 'manage_woocommerce',
        'edit_terms'                 => 'manage_woocommerce',
        'delete_terms'               => 'manage_woocommerce',
        'assign_terms'               => 'manage_woocommerce',
    ); 
 
// Now register the taxonomy
     $args = array(
        'labels'                     => $labels,
        'show_in_rest'               => true,       
        'hierarchical'               => true,
        'public'                     => true,
        'show_ui'                    => true,
        'show_admin_column'          => false,
        'show_in_nav_menus'          => true,
        'show_tagcloud'              => true,
        'capabilities'               => $capabilities,
        
    
    );
    register_taxonomy( 'brands', array( 'product' ), $args );
    register_taxonomy_for_object_type( 'brands', 'product' );

 
}

Register Taxonomy API for WC

//Register taxonomy API for WC
add_action( 'rest_api_init', 'register_rest_field_for_custom_taxonomy_brands' );
function register_rest_field_for_custom_taxonomy_brands() {
    

    register_rest_field('product', "brands", array(
        'get_callback'    => 'product_get_callback',
        'update_callback'    => 'product_update_callback',
        'schema' => null,
    ));    

}
        //Get Taxonomy record in wc REST API
         function product_get_callback($post, $attr, $request, $object_type)
        {
            $terms = array();

            // Get terms
            foreach (wp_get_post_terms( $post[ 'id' ],'brands') as $term) {
                $terms[] = array(
                    'id'        => $term->term_id,
                    'name'      => $term->name,
                    'slug'      => $term->slug,
                    'custom_field_name'  => get_term_meta($term->term_id, 'custom_field_name', true)
                );
            }

            return $terms;
        }
        
         //Update Taxonomy record in wc REST API
         function product_update_callback($values, $post, $attr, $request, $object_type)
        {   
            // Post ID
            $postId = $post->get_id();
            
            //Example: $values = [2,4,3];                
            
            // Set terms
           wp_set_object_terms( $postId, $values , 'brands');
            
            
        }

Solution above is working but you have to change the

$postId = $post->get_id();

with

$postId = $post->ID;

Took me ages to find out why update_callback did not work : $values contains the taxonomy-structure and is therefore too complex to pass as integer to wp_set_object_terms. You have to strip it to the numeric ID's only otherwise [null] is assigned

//Update Taxonomy record in wc REST API
     function product_update_callback_Leerjaar($values, $post, $attr, $request, $object_type)
    {   
        // Post ID            
        $postId = $post->id;
        
        //Example: $values = [2,4,3];    
 
         error_log("debug on values");
         error_log(json_encode($values));
                         
         $numarray = [];             
         foreach($values as $value){
             $numarray[] = (int)$value['id'];
         }
          
       wp_set_object_terms( $postId, $numarray , 'brands');
        
        
    }

If anyone has tested all the above and can't get it to work, I found a simplest and working solution, based on Taha Farooqui's answer and the wordpress register_rest_field documentation :

add_action( 'rest_api_init', 'register_rest_field_for_custom_taxonomy_brands');
function register_rest_field_for_custom_taxonomy_brands() {
    register_rest_field('product', "field_rest_name",
        array("get_callback" => function ($post) {
            $taxonomy = wp_get_post_terms( $post['id'], 'your_taxonomy_name');
                return $taxonomy;
            }
        )
    );
}
Related