skip to Main Content

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 ?

5

Answers


  1. Chosen as BEST ANSWER

    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');
                
                
            }
    

  2. Solution above is working but you have to change the

    $postId = $post->get_id();
    

    with

    $postId = $post->ID;
    
    Login or Signup to reply.
  3. 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');
            
            
        }
    
    Login or Signup to reply.
  4. 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;
                }
            )
        );
    }
    
    Login or Signup to reply.
  5. After months of testing trying to prove why the product_update_callback() function returned a null value, he got a version that loads the taxonomy values ​​from the woocommerce Rest Api v3 only with the name and slug..

    <?php
    //Prevent a malicious user from executing php code from the browser bar
    defined('ABSPATH') or die( "Bye bye" );
    
    
    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
     
      $labels = array(
        'name' => _x( 'Marcas', 'taxonomy general name' ),
        'singular_name' => _x( 'Marca', 'taxonomy singular name' ),
        'search_items' =>  __( 'Buscar Marcas' ),
        'all_items' => __( 'Todas las Marcas' ),
        'parent_item' => __( 'Marca Relacionada' ),
        'parent_item_colon' => __( 'Marca Relacionada:' ),
        'edit_item' => __( 'Editar Marca' ), 
        'update_item' => __( 'Subir Marca' ),
        'add_new_item' => __( 'Añadir Nueva Marca' ),
        'new_item_name' => __( 'Nuevo Nombre de Marca' ),
        'menu_name' => __( 'Marcas' ),
      );    
      
        $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( 'pwb-brand', array( 'product' ), $args );
        register_taxonomy_for_object_type( 'pwb-brand', 'product' );
    
     
    }
    
    
    //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', "pwb-brand", array(
            'get_callback'    => 'product_get_callback_brand',
            'update_callback'    => 'product_update_callback_brand',
            'schema' => null,
        ));    
    
    }
    
    
    
            //Get Taxonomy record in wc REST API
    function product_get_callback_brand($post, $attr, $request, $object_type){
                
        $terms = array();
    
                // Get terms
                foreach (wp_get_post_terms( $post[ 'id' ],'pwb-brand') as $term) {
                    $terms[] = array(
                        'id'        => $term->term_id,
                        'name'      => $term->name,
                        'slug'      => $term->slug,
                    );
                }
    
                return $terms;
    }
    
    
    
    //Update Taxonomy record in wc REST API
    function product_update_callback_brand($values, $post, $attr, $request, $object_type){   
        // Post ID            
        $postId = $post->id;
    
        $terms = $values;
        
        $termName = $terms[0]['name'];
        $termSlug = $terms[0]['slug'];
    
        wp_insert_term( $termName, 'pwb-brand', array( 'slug' => $termSlug ) );
    
         error_log("debug on values");
         error_log(json_encode($values));
    
         $newTermId = get_term_by('slug',$termSlug,'pwb-brand')->term_id;
    
         array_push($values, array('id' => (int)$newTermId));
                         
         $numarray = [];             
         foreach($values as $value){         
             if(is_numeric($value['id'])){             
                 $numarray[] = (int)$value['id'];          
             }       
        }
          
       wp_set_object_terms( $postId, $numarray , 'pwb-brand');
    }
    
    

    After so much testing he understood that the values ​​that pass through the product_get_callback_brand function are mandatory to register a taxonomy so if you add a custom field like in the first example then they must be loaded so that the taxonomy can be retrieved.

    It is worth noting that it is not a valid field for image fields or galleries that will not have the permissions to be loaded by the Rest Api v3 of woocommerce

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search