WooCommerce Cart - Dynamic Price variable pass into custom price hook

后端 未结 2 868
难免孤独
难免孤独 2021-01-14 11:26

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 i

2条回答
  •  一向
    一向 (楼主)
    2021-01-14 11:51

    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.

提交回复
热议问题