'Woocommerce programmatically added attributes to grouped product not showing on admin area
I was able to add attribute value programmatically to the product and it was showing on the front but not showing in the admin area attributes.
Do I need to assign attributes to the product before adding attribute value?
add_action('woocommerce_before_product_object_save', 'nd_update_group_product_attributes_before_save_func', 1001, 2);
function nd_update_group_product_attributes_before_save_func($product, $data_store) {
// exit if not the target post type
if ('product' !== $post->post_type || wp_is_post_revision( $post_ID )) {
return;
}
$product_type = $product->get_type();
if ($product->is_type('grouped')) {
$child_product_ids = $product->get_children();
$all_child_bed_attributes = array();
$all_child_bath_attributes = array();
foreach ($child_product_ids as $child_product_id) {
$child_product = wc_get_product($child_product_id);
// $pa_bedrooms = $child_product->get_attribute('pa_bedrooms');
$pa_bedrooms = wc_get_product_terms( $child_product_id, 'pa_bedrooms', array( 'fields' => 'names' ) );
$pa_bathrooms = wc_get_product_terms( $child_product_id, 'pa_bathrooms', array( 'fields' => 'names' ) );
$all_child_bed_attributes = array_unique(array_merge($all_child_bed_attributes, $pa_bedrooms));
$all_child_bath_attributes = array_unique(array_merge($all_child_bath_attributes, $pa_bathrooms));
}
if ($all_child_bed_attributes) {
foreach ($all_child_bed_attributes as $bed) {
wp_set_object_terms($product->get_id(), $bed, 'pa_bedrooms', true);
}
}
if ($all_child_bath_attributes) {
foreach ($all_child_bath_attributes as $bath) {
wp_set_object_terms($product->get_id(), $bath, 'pa_bathrooms', true);
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
