I've been trying to implement a solution for setting taxonomy attributes on WooCommerce products. This is a the code I wrote:
$product = wc_get_product($product_id);
$taxonomy = 'pa_out-of-stock';
$false_term_name = 'false';
$true_term_name = 'true';
$false_term_id = get_term_by('name', $false_term_name, $taxonomy)->slug;
$true_term_id = get_term_by('name', $true_term_name, $taxonomy)->slug;
$attributes = (array) $product->get_attributes();
if (array_key_exists($taxonomy, $attributes)) {
foreach (
$attributes as $key => $attribute
) {
if ($key == $taxonomy) {
$options = $attribute->get_options();
$options = array($true_term_id);
$attribute->set_options($options);
$attributes[$key] = $attribute;
break;
}
}
$product->set_attributes($attributes);
}
else {
$attribute = new WC_Product_Attribute();
$attribute->set_id(sizeof($attributes) + 1);
$attribute->set_name($taxonomy);
$attribute->set_options(array($false_term_id));
$attribute->set_position(sizeof($attributes) + 1);
$attribute->set_visible(true);
$attribute->set_variation(false);
$attributes[] = $attribute;
$product->set_attributes($attributes);
}
$product->save();
I printed out the $product object and the set_options()
function seems to be changing the value. But after the $product->save()
function is called there seems to be no changes, the attribute term doesn't seem to change on the product. I checked the term ID's, they are correct. I checked the taxonomy slug, it also correct. The just seems that the saving is not working. Any ideas why this could be happening?