如何从一个变体中获取某个属性的值?

前端开发 2026-07-10

在我正在开发的一个插件里,我在一个变体上添加了两个属性。一个是仅针对该变体的,另一个则是全局性的(任意值)。当我尝试从变体中获取这些值时(客户选定后),可以得到该特定属性的值,但全局属性的值却拿不到。

add_filter( 'woocommerce_get_price_html', 'bbloomer_alter_price_display', 9999, 2 );
function bbloomer_alter_price_display( $price, $product ) {
        if ( $product->is_type( 'simple' ) || $product->is_type( 'variation' ) ) {   
            $attributes = wc_get_product_variation_attributes($product->get_id());
            error_log(print_r($attributes, true));
}

结果是:

Array
(
    [attribute_pa_ringmaat] => 3
    [attribute_pa_material] => 
)

我猜这是因为属性其实是在父级上设定的,但我找不到从父级取得它的方法。我尝试了好几种方法,其中包括:

            $parent_id = $product->get_parent_id();
            $parent = wc_get_product($parent_id);       

            $material = $parent->get_meta( 'pa_material' );

我到底还缺少什么?

解决方案

你现有的WordPress网站已经内置了REST API,因此在WordPress端不需要做任何修改。该API现在就已经在yoursite.com/wp-json/wp/v2/posts上可用。

在你的React应用中,可以像下面这样获取文章:

const res = await fetch('https://yoursite.com/wp-json/wp/v2/posts?per_page=10&_embed');
const posts = await res.json();

参数 _embed 可以在一次请求中同时拉取特色图片和作者数据,从而避免额外的API调用。

有几点需要注意:

  1. CORS — WordPress默认会阻止跨域请求。把下面的代码加入你主题的functions.php:
add_action('init', function() {
      header('Access-Control-Allow-Origin: https://your-react-domain.com');
      header('Access-Control-Allow-Methods: GET');
  });

或者使用 rest_pre_serve_request 过滤器以获得更细的控制。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章