wordpress 在woocommerce REST API中添加自定义分类术语

l3zydbqr  于 2023-01-16  发布在  WordPress
关注(0)|答案(5)|浏览(222)

我已经创建了自定义分类“品牌”并附加到woocommerce产品。不幸的是,它在woocommerce REST API响应中不可用。如何将自定义分类术语附加到woocommerce REST API。目前没有关于自定义分类附件的文档。有任何钩子或过滤器吗?

wwtsj6pe

wwtsj6pe1#

我解决了使用这个代码。你将能够获得和更新自定义分类使用这个方法。基本上。你可以添加这个代码在functions.php文件或在plugin

步骤:1brands替换为您的taxonomy_name
步骤:2如果您的分类具有自定义字段,请将custom_field_name替换为您的字段。
分类编码:

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

 
}

为WC注册分类API

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

wi3ka0sx2#

以上解决方案有效,但您必须更改

$postId = $post->get_id();

$postId = $post->ID;
bzzcjhmw

bzzcjhmw3#

我花了很长时间才找到update_callback不起作用的原因:$values包含分类结构,因此过于复杂,无法作为整数传递给wp_set_object_terms。您必须将其剥离为数字ID,否则将分配[null

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

0qx6xfy64#

如果有人已经测试了以上所有的方法,但还是不能让它工作,我找到了一个最简单的解决方案,基于Taha Farooqui的答案和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;
            }
        )
    );
}
ycl3bljg

ycl3bljg5#

经过几个月的测试,试图证明product_update_callback()函数返回空值的原因,他得到了加载分类值的版本 从woocommerce休息api v3只与名称和鼻涕虫。

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

经过这么多测试他明白了 通过product_get_callback_brand函数传递的字段是注册分类法所必需的,因此如果像第一个示例那样添加自定义字段,则必须加载这些字段,以便检索分类法。
值得注意的是,它不是一个有效的图像字段或画廊,将不会有权限被加载的Rest Api v3的woocommerce

相关问题