0
votes

i want to apply attribute programmatically in woocommerce, for that i have used this code but it is not working, can anyone please look my code and help me to resolve this issue ?

$product_id = 4931;
    $attribute_name = "test_attribute";
    $attribute_value = "test_attribute";
    $term_taxonomy_ids = wp_set_object_terms($product_id, $attribute_value, $attribute_name, true);
    $data = array(
    $attribute_name => array(
    'name' => $attribute_name,
    'value' => '',
    'is_visible' => '1',
    'is_variation' => '0',
    'is_taxonomy' => '1'
    )
    );
    //First getting the Post Meta
    $_product_attributes = get_post_meta($product_id, '_product_attributes', TRUE);
    //Updating the Post Meta
    update_post_meta($product_id, '_product_attributes', array_merge($_product_attributes, $data));
}
1

1 Answers

0
votes

I recommend to use the wc-functions to handle product data, because in future product data maybe not in wp_post and wp_post_meta table anymore.

$product_id = 4931;

$p = wc_get_product( $product_id );
$my_custom_value = $p->get_meta('_custom_value');

// to change the costum attribute
$p->update_meta_data('_custom_value', $my_new_value );
$p->save();

This links has usefull information:

wc_get_products and WC_Product_Query

Accessing WC_Product protected data in Woocommerce 3