WooCommerce Cart - Dynamic Price variable pass into custom price hook
Asked Answered
R

3

3

I am getting the dynamic custom price in a variable that I want to pass to the hooked function in woocommerce_before_calculate_totals hook in cart. But it isn't working.

This is my code:

  $add=200; //I want to pass this variable in add_action hook
  add_action( 'woocommerce_before_calculate_totals', 'add_custom_total_price');
  function add_custom_total_price($cart_object) {
     global $woocommerce;
     $custom_price =$add; // This is my custom price
    foreach ( $cart_object->cart_contents as $key => $value ) {
       $value['data']->price = $custom_price;
    }
 } 

How can I achieve this?

Thanks

Rationalize answered 2/8, 2016 at 9:0 Comment(2)
i have tried your answer is working fine.. right now i am not using this method.i was using variation..Rationalize
#38913052 please suggest me this question woocommerce.ThanksRationalize
C
2

To make it work you just need to define $custom_price variables as global in your function, this way:

$custom_price = 200; 

add_action( 'woocommerce_before_calculate_totals', 'add_custom_item_price', 10, 1 );
function add_custom_item_price( $cart_object ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    global $custom_price;

    foreach (  $cart_object->get_cart() as $item_values ) {
        $item_values['data']->price = $custom_price;
    }
} 

This code is tested and working (for woocommerce versions 2.5+ and 2.6+).

Naturally this code goes on function.php file of your active child theme or theme.

Carbamidine answered 3/8, 2016 at 23:48 Comment(0)
A
0

To add Price in your woocommerce cart before calculate total -

 add_action( 'woocommerce_before_calculate_totals', 'add_custom_total_price');

  function add_custom_total_price($cart_object) {
     global $woocommerce,$add,$custom_price; 
     $add=200;//Dynamic Price variable
     $custom_price =$add;//Dynamic Price variable pass to custom price
    foreach ( $cart_object->cart_contents as $key => $value ) {
       $value['data']->price = $custom_price;
    }
 } 
Araucanian answered 4/8, 2016 at 10:37 Comment(0)
G
0

Use set_price() method to set it for the new version.

add_action( 'woocommerce_before_calculate_totals', 'add_custom_total_price', 10 );
function add_custom_total_price( $cart_object ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $framed_price = 20;

    foreach ( $cart_object->get_cart() as $key => $value ) {
        $value['data']->set_price( $framed_price );
    }
}
Gutsy answered 31/5, 2024 at 13:19 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.