1
votes

I have two shipment class for my products based on their category. Each time after updating a product, it loose the shipment class and I have no idea why.

However I tried to assign proper shipment class to products "on save" programmatically:

  • specified categories => 1001
  • else => 1002

Here is my code:

add_action( 'added_post_meta', 'woo_on_product_save', 10, 4 );
add_action( 'updated_post_meta', 'woo_on_product_save', 10, 4 );

function woo_on_product_save( $meta_id, $post_id, $meta_key, $meta_value ) {
    if ( $meta_key == '_edit_lock' ) {
        if ( get_post_type( $post_id ) == 'product' ) { 
            if (has_term('fastfood','product_cat')||has_term('coffee','product_cat')){
            $shipping_class_type=1001;
    }
    else{
        $shipping_class_type=1002;
    }
            $product = wc_get_product( $post_id );
            $product->set_shipping_class_id( $shipping_class_type );
            $product->save();
        }
    }
}

But this doesn't work as expected. When I make changes on any product(Even products in specified categories) the shipment class always become 1002.

Can you tell me what I am doing wrong?

1

1 Answers

1
votes

Updated - Instead try the following with a different hook (untested):

add_action( 'woocommerce_process_product_meta', 'woo_on_product_save', 100 );
function woo_on_product_save( $post_id ) {
    if ( has_term( array('fastfood', 'coffee'), 'product_cat', $post_id ) ) {
        $shipping_class_id = 1001;
    } else {
        $shipping_class_id = 1002;
    }
    $product = wc_get_product( $post_id );
    $product->set_shipping_class_id( $shipping_class_id );
    $product->save();
}

Code goes in functions.php file of the active child theme (or active theme). It could works.

Note: you need to be sure that 1001 and 1002 exist as shipping class ID.