编程语言
首页 > 编程语言> > php – 在Woocommerce中通过变体ID获取属性slug值

php – 在Woocommerce中通过变体ID获取属性slug值

作者:互联网

我正在构建自定义产品页面,但我遇到了各种变化问题

这是我的代码:

global $product;
$variations = $product->get_available_variations();

foreach($variations as $variation)
{

     $variation_id = $variation['variation_id'];

     $variation_obj = new WC_Product_variation($variation_id);

     //THIS IS PROBLEM FAIL TEST (It's exemple)
     $type = $variation_obj->get_attributes()->get_name();
     //-----

     $stock = $variation_obj->get_stock_quantity();
     $COD = $variation_obj->get_sku();
     $regularprice = $variation_obj->get_regular_price();
     $saleprice = $variation_obj->get_sale_price();
     $diff = $regularprice-$saleprice;

     echo "<p>Variation: " .$type."</p>";
     echo "<p>P.Code: " .$COD."</p>";
     echo "<p>Regular price: ".$regularprice."</p>";
     echo "<p>Sale price: ".$saleprice."</p>";
     echo "<p>Difference: ". $diff."</p>";
     echo "<p>Stock: ".$stock."</p>";
}

我想知道是否可以提取属性或变体的单个名称?

或者没有完整标题的变体名称?

例:
我想要“蓝色”……而不是“魔法美丽的Pouf Lumaland – 蓝色”

任何形式的帮助将不胜感激.

解决方法:

属性slug值数组包含在$variation数组中.所以试试这个:

global $product;
if($product->is_type('variable')){
    $variations = $product->get_available_variations();

    foreach($variations as $variation)
    {
        $variation_obj = wc_get_product($variation['variation_id']);

        // Variation can have many poduct attributes
        $attr_slugs = implode(', ', $variation['attributes']);

        $stock = $variation_obj->get_stock_quantity();
        $COD = $variation_obj->get_sku();
        $regularprice = $variation_obj->get_regular_price();
        $saleprice = $variation_obj->get_sale_price();
        $diff = $regularprice-$saleprice;

        echo "<p>Var Name: " .$attr_slugs."</p>";
        echo "<p>Var Name: " .$COD."</p>";
        echo "<p>regular price: ".$variation['display_regular_price']."</p>";

        echo "<p>sale price: ".$saleprice."</p>";
        echo "<p>risparmi: ". $diff."</p>";
        echo "<p>in stock: ".$stock."</p>";
    }
}

经过测试和工作.

标签:php,wordpress,woocommerce,custom-taxonomy,variations
来源: https://codeday.me/bug/20190910/1801050.html