Search code examples
phpwordpresswoocommercecarthook-woocommerce

Get value of an array when changing price via woocommerce_before_calculate_totals


So i have an array of products with there respectable sale price.

Normally getting value from an array is simple as below:

$the_sups = array(
    21179 => 14.99,     //shine
    21169  => 17.95,    //boost
    1665  => 19.15,     //flexx
    1663  => 17.85,     //revive
    1661 => 19.75,      //muscle
    1657  => 17.85      //maximus
);
echo $the_sups[21179];

Which will return 14.99

And for the life of me i keep get a getting return of NULL when passing though the woocommerce_before_calculate_totals

Below is code im using which i know should work if the price is returned from the array:

$sup_discount= 0.9;

$the_sups = array(
    21179 => 14.99,     //shine
    21169  => 17.95,    //boost
    1665  => 19.15,     //flexx
    1663  => 17.85,     //revive
    1661 => 19.75,      //muscle
    1657  => 17.85      //maximus           
);

foreach (WC()->cart->get_cart() as $hash => $value ) {

    if( in_array( 52, $value['data']->get_category_ids() ) ) {

         echo $value['product_id'];  //IS 21179

         $product_value = $the_sups[$value['product_id']];
         var_dump($product_value); //IS ALWAYS NULL

         $value['data']->set_price($product_value * $sup_discount);

    }         
}  

Could someone explain what i am doing wrong?


Solution

  • This seems to do it, tested with WooCommerce 4.1.0

    function action_woocommerce_before_calculate_totals( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    
        if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
    
        /* SETTINGS */
    
        $sup_discount = 0.9;
    
        $the_sups = array(
            21179  => 14.99, // shine
            21169  => 17.95, // boost
            1665   => 19.15, // flexx
            1663   => 17.85, // revive
            1661   => 19.75, // muscle
            1657   => 17.85, // maximus
        );
    
        /* END SETTINGS */
    
        // Loop through cart items
        foreach ( $cart->get_cart() as $value ) {    
            // Get product id
            $product_id = $value['product_id'];
    
            if( in_array( 52, $value['data']->get_category_ids() ) ) {
                echo $product_id;
    
                $product_value = $the_sups[ $product_id ];
    
                var_dump($product_value);
    
                $value['data']->set_price( $product_value * $sup_discount );
            }
        }
    }
    add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );