I'm building a custom product page but I have problems with variations
This is my code:
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>";
}
I am wondering if it is possible to extract the single name of the attribute or variation ?
or the name of the variation without the full title?
example: I want "blue"... not "Magic beautiful Pouf Lumaland - blue"
The array of attributes slug values is included in the $variation
array. So try this instead:
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>";
}
}
Tested and works.