Matthew M
Matthew M

Reputation: 381

Woocommerce change price based on quantity and variation

I am currently creating my first site using woocommerce for a client, and they are requesting for me to have a price increase per variation and quantity, however i am not sure how to do it. Here is an example of what they are asking for:

Product Type: Limestone

Variations:

TL;DR if the customer wants multiple 10kg bags, the price increases by £36 at a time, if they want multiple 20kg bags, the price increases by £30 at a time, and if they want multiple 40kg bags, the price doubles every time.

I have used woocommerce variations and attributes so far but now it would require modifying having 3x20 variations all of which require a different price, which would be easier to change if a statement is possible as follows:

if ($productsize === '10kg') {
   $quantity = 2; //get quantity from textbox $_POST
   $initial_price = 36; //get inital price from woocommerce global variable
   
   $total_price = $inital_price * $quantity;

   update_price($total_price); //a function to update the price in woocommerce when adding to cart
   
}

Obviously the code above does not use any woocommerce variables, however doing this for only 3 variations would be easier than manually entering 60 variations on one product for which we have >60 on our site.

Upvotes: 3

Views: 9035

Answers (1)

Morticella
Morticella

Reputation: 69

I don't know if you need it anymore, however try it

add_action( 'woocommerce_before_calculate_totals', 'IG_recalculate_price',5,1 );

function IG_recalculate_price( $cart_object ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
    return;
    $quantity = 0;


    foreach ( $cart_object->get_cart() as $key => $value ) {
            // count q.ty
            $quantity += $value['quantity'];
         // delta q.ty  
        if( $quantity > 24 ) {
           // get price by custom field but you can use a simple var
            $newprice = get_post_meta( $value['data']->get_id(), 'custom_field2', true);
            $value['data']->set_price( $newprice );
           // reset q.ty for check every item in the cart
            $quantity = 0;

                    }else{

            $newprice = get_post_meta( $value['data']->get_id(), 'custom_field', true);
            $value['data']->set_price( $newprice );
            $quantity = 0;

            }
        }
    }

Upvotes: 1

Related Questions