Search code examples
phpwoocommerceproductcustom-taxonomy

Change cart item prices based on specific product attribute value in Woocommerce


I am trying to change product price in cart using the following function:

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 10);
function add_custom_price( $cart_obj ) {
    foreach ( $cart_obj->get_cart() as $key => $value ) {
        $item_data = $value['data'];
        $price0 = $item_data->get_attributes('per_one_price');
        $price  = (int) $price0;
        $value['data']->set_price( $num_int );
    }
}

But for any number I set as product attribute value for per_one_price attribute I get the number 1 in cart price.


Solution

  • Update - There is 2 little mistakes:

    • Replace get_attributes() by get_attribute() (singular).
    • Replace 'per_one_price' by 'Per one price' (or 'per-one-price' as blank spaces are replaced by dashes)

    So instead try the following:

    add_action( 'woocommerce_before_calculate_totals', 'set_custom_item_price', 20, 1 );
    function set_custom_item_price( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
            return;
    
        // Loop through cart items
        foreach ( $cart->get_cart() as $cart_item ) {
            // get attibute value
            $new_price = $cart_item['data']->get_attribute('per-one-price');
    
            if( ! empty( $new_price ) ){
                // Set the new price
                $cart_item['data']->set_price( $new_price );
            }
        }
    }
    

    Code goes in function.php file of your active child theme (or active theme). tested and works.


    Create "Per one price" product attribute:

    enter image description here

    The product price setting view:

    enter image description here

    The product attribute set in the product with its value:

    enter image description here

    The cart page view with this product:

    enter image description here