
[英]Modify WooCommerce's API REST response only for specific client/key
[英]How to limit the response's fields from woocommerce rest API?
我需要限制woo commerce Rest API的响应字段。 例如。 当我需要展示特定类别的产品时。 我只需要产品 ID、图像和 slug。 所以,我只想得到特定的领域。 有什么办法可以解决我的问题?
您可以使用过滤器钩子woocommerce_rest_prepare_product_object来调整响应。
$wc_rest_api->get('products', array('category' => '1234', 'fields_in_response' => array(
'id',
'images',
'slug'
) ) );
默认情况下,参数fields_in_response
不存在。 以下代码必须放在服务器端(即在functions.php 中)才能使用。
add_filter('woocommerce_rest_prepare_product_object', 'at_wc_rest_api_adjust_response_data', 10, 3);
function at_wc_rest_api_adjust_response_data( $response, $object, $request ) {
$params = $request->get_params();
if ( ! $params['fields_in_response'] ) {
return $response;
}
$data = $response->get_data();
$cropped_data = array();
foreach ( $params['fields_in_response'] as $field ) {
$cropped_data[ $field ] = $data[ $field ];
}
$response->set_data( $cropped_data );
return $response;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.