The data is in a strange way, where it just checks if the product name is the same while going through the items in the JSON, and if it does, it adds the attributes of that item to the product with the same name. But right now it only shows the last attributes added in WooCommerce.
Imagine one of the items has two attributes, color and grade, and they’re Red and Grade A, and then another item afterwards that has the same name as the first one, but different color and grade, like Yellow and Grade B, so its the same product, but different variation, but for some reason only the last variation attributes go through to WooCommerce.
function insert_product_attributes($post_id, $available_attributes, $variations) {
$existing_attributes = get_post_meta($post_id, '_product_attributes', true);
error_log('existing attributes for the product ' . get_the_title($post_id) . ' : ' . print_r($existing_attributes, true));
if (!$existing_attributes) {
$existing_attributes = array();
}
$attribute_values = array();
foreach ($available_attributes as $attribute) {
$values = array();
foreach ($variations as $variation) {
$attribute_keys = array_keys($variation['attributes']);
foreach ($attribute_keys as $key) {
if ($key === $attribute) {
$values[] = $variation['attributes'][$key];
}
}
}
$values = array_unique($values);
$attribute_values[$attribute] = $values;
wp_set_object_terms($post_id, $values, 'pa_' . sanitize_title($attribute));
}
$product_attributes_data = array();
foreach ($available_attributes as $attribute) {
$attribute_name = 'pa_' . sanitize_title($attribute);
$existing_values = array();
if (isset($existing_attributes[$attribute_name])) {
if (!empty($existing_attributes[$attribute_name]['value'])) {
$existing_values = explode(' | ', $existing_attributes[$attribute_name]['value']);
}
}
$all_values = array_unique(array_merge($existing_values, $attribute_values[$attribute]));
error_log('all attributes: ' . print_r($all_values, true));
$product_attributes_data[$attribute_name] = array(
'name' => $attribute_name,
'value' => implode(' | ', $all_values),
'is_visible' => '1',
'is_variation' => '1',
'is_taxonomy' => '1'
);
}
update_post_meta($post_id, '_product_attributes', $product_attributes_data);
}
Markuss Ilgažs is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.