phpwordpresswoocommercetaxonomy-terms

Saving product attributes with Woocommerce methods not syncing to front end


This is not a duplicate question.

The problem here is not adding the attributes per say. The problem is associating the added attribute options with the proper terms I guess. As can be seen in the pictures below, the attribute options are set correctly but they are not associated with their terms (as seen in picture one [text instead of the gray background attribute option as seen in picture three]) even though I manually run set_object_terms for each product and the relationship is set properly in the database.

foreach($terms as $term_id) {
    $term = get_term( $term_id );
    $term_name = $term->name;
    $term_taxonomy = $term->taxonomy;
    $term_slug = $term->slug;
                            
    if( ! has_term( $term_name, $term_taxonomy, $parent_id ) ) {
        $set_terms = wp_set_object_terms($parent_id, $term_slug, $term_taxonomy, true );
    }
                            
}

While working on transferring some attributes from one database to another I'm facing an issue with the fact that attributes are being transferred correctly but they are saved in text form...

enter image description here

and I need to manually click "Save attributes" in wordpress admin > product edit...

enter image description here

for it to actually register correctly in the system as can be seen here.

enter image description here

The main issue is that while in text form as shown in the first screenshot, the attributes are not actually visible in the user facing shop and they are not available in the product's variations either.

I'm using woocommerce methods to update the products. Here's a code sample:

$attribute_object = new WC_Product_Attribute();
$attribute_object->set_name( $attribute_name );
$attribute_object->set_options( $value );
$attribute_object->set_visible(1);
$attribute_object->set_variation(1);
$attribute_object->set_position(0);
$attribute_object->set_id( 0 );
$new_product_attributes[$attribute_name] = $attribute_object;
$new_product->set_attributes($new_product_attributes);
                        
$new_product->save();

How can I get WP to sync the product with it's newly added attributes/attribute values?


Solution

  • For anyone having the same issue, it took me a while but I finally figured it out. In the example above there's one property that's missing from the wc_product_attribute object:

    $attribute_object->set_id($taxonomy_id);
    

    Also the value for set_options should be enclosed in an array:

    $attribute_object->set_options( [$value] );
    

    Hopefully this will be useful for someone else facing the same issue.