Skip to content
Advertisement

WooCommerce Update Group product attributes by child products

HOOK: Add child product attributes values to group product on saving

add_action( 'save_post_product', 'nd_update_group_product_attributes_func', 1002, 3 ); 

function nd_update_group_product_attributes_func($post_ID, $post, $update){

    if ('product' !== $post->post_type || wp_is_post_revision( $post_ID )) {
        return;
    }

    $product = wc_get_product( $post_ID );

    if( $product->is_type( 'grouped' ) ) {

        $child_product_ids   = $product->get_children();
        $all_child_bed_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' );
            $all_child_bed_attributes = array_unique(array_merge($all_child_bed_attributes, $pa_bedrooms));

        }
        if($all_child_bed_attributes){
        
            foreach($all_child_bed_attributes as $bed){
                wp_set_object_terms( $post_ID, $bed, 'pa_bedrooms',true );
            }

        }

    }
}

The above code will update the pa_bedrooms attribute on the Group product on the update, not on the first creation.

Can anyone tell me what I am missing here?

Advertisement

Answer

add_action('woocommerce_before_product_object_save', 'nd_update_group_product_attributes_func', 10, 2);

function nd_update_group_product_attributes_func($product, $data_store) {

    $product_type = $product->get_type();
    if ($product->is_type('grouped')) {

        $child_product_ids = $product->get_children();
        $all_child_bed_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');
            $all_child_bed_attributes = array_unique(array_merge($all_child_bed_attributes, $pa_bedrooms));
        }
        if ($all_child_bed_attributes) {

            foreach ($all_child_bed_attributes as $bed) {
                wp_set_object_terms($post_ID, $bed, 'pa_bedrooms', true);
            }
        }
    }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement