根据Woocommerce中的ID获得产品的所有产品变体

qbr*_*qbr 4 wordpress woocommerce

我有一个自定义页面,我试图在其中列出商店中的所有产品及其变体。

另外,我正在尝试列出按产品属性排序的变化价格,并附带“大小”

为了进行测试,我试图获取ID为381的单个产品的版本。我的代码是

    $handle=new WC_Product('381');
    $variations1=$handle->get_avaialable_variations();
    foreach ($variations1 as $key => $value) {
            echo '<option  value="'.$value['variation_id'].'">'.implode('/',$value['attributes']).'-'.$value['price_html'].'</option>';

    }
Run Code Online (Sandbox Code Playgroud)

但是我得到的错误是

PHP Fatal error:  Call to undefined method WC_Product::get_avaialable_variations() 
Run Code Online (Sandbox Code Playgroud)

我尝试使用

$handle=new WC_Product_Variable('381');
Run Code Online (Sandbox Code Playgroud)

代替

 $handle=new WC_Product('381'); 
Run Code Online (Sandbox Code Playgroud)

但是错误是相同的。

这里有什么帮助吗?

Wis*_*abs 6

试试这个代码。

    $handle=new WC_Product_Variable('12');
        $variations1=$handle->get_children();
        foreach ($variations1 as $value) {
        $single_variation=new WC_Product_Variation($value);
            echo '<option  value="'.$value.'">'.implode(" / ", $single_variation->get_variation_attributes()).'-'.get_woocommerce_currency_symbol().$single_variation->price.'</option>';
}
Run Code Online (Sandbox Code Playgroud)

注意:使用此$ single_variation-> get_price_html(),但其输出带有html span标记将导致隐藏在选项标记中。

测试了上面的代码,结果如下。

让我知道这是否对您也有用。

在此处输入图片说明