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

WooCommerce REST API如何筛选含特定元数据的商品?

WooCommerce REST API 筛选自定义元数据商品方案

问题本质

你通过ACF添加的condition是商品元数据,而非WooCommerce原生的产品属性,所以用原生API的attribute、attribute_term参数完全无效——这两个参数仅针对WooCommerce内置的产品属性(如尺寸、颜色)设计。

实现方式

WooCommerce REST API v3本身不支持直接筛选元数据,但可以通过以下两种方式实现需求:

1. 自定义API端点(推荐)

在主题functions.php或自定义插件中添加代码,注册支持元数据筛选的自定义端点:

add_action( 'rest_api_init', function () {
  register_rest_route( 'wc/v3', '/products/filter-by-condition', array(
    'methods' => 'GET',
    'callback' => 'filter_products_by_condition',
    'permission_callback' => function () {
      return current_user_can( 'manage_woocommerce' );
    },
  ) );
} );

function filter_products_by_condition( $request ) {
  $condition = $request->get_param( 'condition' );
  $args = array(
    'post_type' => 'product',
    'posts_per_page' => -1,
    'meta_query' => array(
      array(
        'key' => 'condition',
        'value' => $condition,
        'compare' => '='
      )
    )
  );
  $products = get_posts( $args );
  $response = array();
  foreach ( $products as $product ) {
    $wc_product = wc_get_product( $product->ID );
    $response[] = $wc_product->get_data();
  }
  return rest_ensure_response( $response );
}

添加完成后,即可通过该端点查询指定条件的商品:

curl "https://你的站点域名/wp-json/wc/v3/products/filter-by-condition?condition=New"

2. 扩展原生API参数

如果不想自定义端点,可通过过滤器扩展原生API,让其支持meta_key和meta_value参数:

add_filter( 'woocommerce_rest_product_object_query', function( $args, $request ) {
  $meta_key = $request->get_param( 'meta_key' );
  $meta_value = $request->get_param( 'meta_value' );
  
  if ( $meta_key && $meta_value ) {
    $args['meta_query'][] = array(
      'key' => $meta_key,
      'value' => $meta_value,
      'compare' => '='
    );
  }
  
  return $args;
}, 10, 2 );

之后直接用原生端点加参数查询:

curl "https://你的站点域名/wp-json/wc/v3/products?meta_key=condition&meta_value=New"

注意事项

  • 确保API请求携带正确的身份验证信息(OAuth1或API密钥)。
  • 确认ACF字段的元数据键与代码中使用的condition一致(ACF默认存储的键就是你设置的字段名)。
  • 自定义代码需做好权限验证,防止未授权访问。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 18:12:18