首页 文章

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

提问于
浏览
3

我有一个自定义页面,我试图列出商店中的每个产品及其变化 .

此外,我正在尝试列出按产品属性排序的变量'价格与slug'尺寸'

为了进行测试,我正在尝试使用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>';

    }

但我得到的错误是

PHP Fatal error:  Call to undefined method WC_Product::get_avaialable_variations()

我试过用

$handle=new WC_Product_Variable('381');

代替

$handle=new WC_Product('381');

但错误是一样的 .

这里有什么帮助?

3 回答

  • 4

    试试这个代码 .

    $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>';
    }
    

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

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

    如果这对您有用,请告诉我 .

    enter image description here

  • 1

    您的代码中有拼写错误 - get_avaialable_variations

    它应该是 get_available_variations

  • 0
    function get_variation_data_from_variation_id($item_id) {
    
        $_product = new WC_Product_Variation($item_id);
        $variation_data = $_product->get_variation_attributes(); // variation data in array
        $variation_detail = woocommerce_get_formatted_variation($variation_data, true);  // this will give all variation detail in one line
        // $variation_detail = woocommerce_get_formatted_variation( $variation_data, false);  // this will give all variation detail one by one
        return $variation_data; // $variation_detail will return string containing variation detail which can be used to print on website
        // return $variation_data; // $variation_data will return only the data which can be used to store variation data
    }
    

    我在stackoverflow之前找到了这个,不记得链接 (please edit if find the link to the answer with this method) . 它显示输出的变化数据 . 该方法将变量id作为参数 .

    output

    enter image description here
    .

相关问题