You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法通过WooCommerce REST API为产品分配自定义分类editoriales

解决WooCommerce REST API无法关联JetEngine自定义分类的问题

问题根源

  • WooCommerce REST API默认未集成自定义分类的自动关联逻辑,即便分类已开启「在REST API中显示」选项
  • 你添加的代码存在参数顺序错误,直接导致500服务器错误
  • register_rest_field的update_callback仅处理产品更新场景,产品创建时需要额外钩子来处理分类关联

修正后的完整代码

// 注册自定义分类到产品的REST字段
add_action( 'rest_api_init', 'register_editoriales_rest_field' );
function register_editoriales_rest_field() {
    register_rest_field( 'product', 'editoriales', array(
        'get_callback'    => 'get_product_editoriales',
        'update_callback' => 'update_product_editoriales',
        'schema'          => array(
            'description' => '自定义分类editoriales的ID列表',
            'type'        => 'array',
            'items'       => array( 'type' => 'integer' )
        ),
    ) );
}

// 获取产品关联的editoriales分类
function get_product_editoriales( $post ) {
    $terms = wp_get_post_terms( $post['id'], 'editoriales', array( 'fields' => 'ids' ) );
    return $terms;
}

// 更新产品的editoriales分类(处理PUT请求)
function update_product_editoriales( $values, $post_object ) {
    if ( ! is_array( $values ) ) {
        return new WP_Error( 'invalid_data', 'editoriales必须是整数数组', array( 'status' => 400 ) );
    }
    wp_set_object_terms( $post_object->ID, $values, 'editoriales', false );
    return $values;
}

// 处理产品创建时的editoriales分类关联(处理POST请求)
add_action( 'woocommerce_rest_insert_product_object', 'set_editoriales_on_product_create', 10, 3 );
function set_editoriales_on_product_create( $product, $request, $creating ) {
    if ( $creating && isset( $request['editoriales'] ) ) {
        $editoriales = $request['editoriales'];
        if ( is_array( $editoriales ) ) {
            wp_set_object_terms( $product->get_id(), $editoriales, 'editoriales', false );
        }
    }
}

关键修正点说明

  • 修正update_callback参数顺序:原代码参数顺序不符合WordPress规范,正确顺序为($value, $post_object, $field_name),多余参数直接触发500错误
  • 添加创建场景钩子:用woocommerce_rest_insert_product_object钩子覆盖产品创建逻辑,弥补register_rest_field只处理更新的缺陷
  • 增加数据验证:确保传入的分类ID是整数数组,避免非法数据导致逻辑异常
  • 简化get_callback:直接返回分类ID数组,和请求格式保持一致,更符合REST API规范

正确的API请求格式

创建产品(POST /wp-json/wc/v3/products)

{
  "product": {
    "name": "测试产品",
    "type": "simple",
    "regular_price": "19.99",
    "editoriales": [1055]
  }
}

更新产品(PUT /wp-json/wc/v3/products/{product_id})

{
  "product": {
    "editoriales": [1055]
  }
}

验证步骤

  1. 将旧代码替换为修正后的版本,保存functions.php
  2. 清理WordPress缓存及浏览器缓存
  3. 发送POST/PUT请求测试,再通过GET请求查看产品的editoriales字段是否正确返回
  4. 登录WordPress后台,确认产品已关联目标分类

内容的提问来源于stack exchange,提问作者Peter Palmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 20:23:27