如何让Woocommerce REST API返回的meta_data属性显示名称而非slug
解决方案
可以通过在主题functions.php文件中添加自定义过滤函数实现,不需要修改WooCommerce核心代码,也不会影响原有业务逻辑。
实现原理
使用WooCommerce提供的woocommerce_rest_prepare_shop_order_object过滤器,在订单接口返回数据前,批量将可变产品的属性slug转换为区分大小写的正式名称,同时兼容全局属性和本地属性两种场景。
完整代码
add_filter('woocommerce_rest_prepare_shop_order_object', 'custom_convert_order_attribute_slug_to_name', 10, 3); function custom_convert_order_attribute_slug_to_name($response, $order, $request) { // 只处理订单接口的GET请求 if ($request->get_method() !== 'GET') { return $response; } $data = $response->get_data(); // 遍历所有商品行项目 foreach ($data['line_items'] as &$line_item) { if (empty($line_item['meta_data'])) continue; foreach ($line_item['meta_data'] as &$meta) { $meta_key = $meta->key; $meta_value = $meta->value; // 处理全局属性(带pa_前缀) if (0 === strpos($meta_key, 'pa_')) { // 获取属性名称 $attribute_obj = wc_get_attribute(str_replace('pa_', '', $meta_key)); if ($attribute_obj) { $meta->key = $attribute_obj->name; } // 获取属性项名称 $term = get_term_by('slug', $meta_value, $meta_key); if ($term && !is_wp_error($term)) { $meta->value = $term->name; } continue; } // 处理本地自定义属性 $product = wc_get_product($line_item['variation_id'] ? $line_item['variation_id'] : $line_item['product_id']); if (!$product) continue; $product_attributes = $product->get_attributes(); foreach ($product_attributes as $attr_key => $attr) { if ($attr_key === $meta_key && !$attr->is_taxonomy()) { // 本地属性的key转正式名称 $meta->key = $attr->get_name(); // 本地属性如果存储的是slug就转名称,已经是名称的不处理 $attr_options = $attr->get_options(); foreach ($attr_options as $option) { if (sanitize_title($option) === $meta_value) { $meta->value = $option; break; } } break; } } } } $response->set_data($data); return $response; }
注意事项
- 上述代码兼容所有PHP 7.0及以上版本,不会干扰Add-ons等第三方插件生成的meta数据返回
- 仅修改REST API接口返回的内容,不会修改数据库中存储的原始数据,不影响WooCommerce后台和其他功能的正常运行
- 建议先在测试环境验证功能正常后再部署到生产环境
内容的提问来源于stack exchange,提问作者rockeypjb
相关产品推荐
相关产品推荐

