In WooCommerce, I'm using $product->get_variation_attributes()
to get the variations attributes for a product. This function returns an array with the names without the ID's.
Like this:
[pa_color-shirt] => Array
(
[0] => red
[7] => grey
[14] => yellow
)
[pa_color-sweater] => Array
(
[0] => red
[1] => green
[2] => blue
[3] => grey
[4] => yellow
[5] => pink
[6] => dark-blue
)
For the AJAX shop I'm creating I also need the ID's from the variations.
So I can append the Id's and the names to the select boxes (Like woocommerce does).
I searched around for days but couldn't find a solution.
I created this code:
if($product->has_child()) {
$attributes = $product->get_attributes();
$variations = $product->get_available_variations();
$variationsArray = array();
foreach ($attributes as $attr => $attr_deets) {
$variationArray = array();
$attribute_label = wc_attribute_label($attr);
$variationArray["attribute_label"] = $attribute_label;
if (isset($attributes[$attr]) || isset($attributes['pa_' . $attr])) {
$attribute = isset($attributes[$attr]) ? $attributes[$attr] : $attributes['pa_' . $attr];
if ($attribute['is_taxonomy'] && $attribute['is_visible']) {
$variationArray["attribute_name"] = $attribute['name'];
$variationIds = array();
$variationNames = array();
$variationPrices = array();
foreach ($variations as $variation) {
if (!empty($variation['attributes']['attribute_' . $attribute['name']])) {
array_push($variationIds, $variation['variation_id']);
$taxonomy = $attribute['name'];
$meta = get_post_meta($variation['variation_id'], 'attribute_'.$taxonomy, true);
$term = get_term_by('slug', $meta, $taxonomy);
$variation_name = $term->name;
array_push($variationNames, $variation_name);
array_push($variationPrices, $variation['display_regular_price']);
}
}
$variationArray["variation_prices"] = $variationPrices;
$variationArray["variations"] = array_combine($variationIds, $variationNames);
}
}
array_push($variationsArray, $variationArray);
}
}
$product_variations = $variationsArray;
This code returns https://hastebin.com/ecebewumoz.php
The code works but returns duplicate names and id's.
My questions is does anyone know how I could accomplish the same as get_variation_attributes()
but with the ID's?
Thanks.