Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
760 views
in Technique[技术] by (71.8m points)

php - Change total woocommerce order weight

I need change total weight of order in woocommerce website.

For example: I have a 3 product in a cart: 1 - 30g; 2 - 35; 3 - 35g; total = 30+35+35 = 100g, but I want to add package weight to total weight (30% from total weight).

Example: ((30+35+35) * 0.3) + (30+35+35) = 130g

I can calculate it, but how change total weight from 100g to 130g.

For getting total weight I use get_cart_contents_weight(), but I don't know how to set new value.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Hook in the right filter action

Let's have a look on the function get_cart_contents_weight():

public function get_cart_contents_weight() {
    $weight = 0;

    foreach ( $this->get_cart() as $cart_item_key => $values ) {
        $weight += $values['data']->get_weight() * $values['quantity'];
    }

    return apply_filters( 'woocommerce_cart_contents_weight', $weight );
}

There is a filter hook we can use: woocommerce_cart_contents_weight

So we can add a function to this filter:

add_filter('woocommerce_cart_contents_weight', 'add_package_weight_to_cart_contents_weight');

function add_package_weight_to_cart_contents_weight( $weight ) {        
    $weight = $weight * 1.3; // add 30%     
    return $weight;     
}

To add the package weight to every product separately, you can try this:

add_filter('woocommerce_product_get_weight', 'add_package_to_product_get_weight');

function add_package_to_product_get_weight( $weight ) {
    return $weight * 1.3;
}

But do not use both solutions together.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...