woocommerce_before_calculate_totals in woocommerce 3.0

I recently made the jump from woocommerce 2.7 to 3.1
I’m having issues with the woocommerce_before_calculate_totals hook on the below function.

function calculate_embossing_fee( $cart_object ) {
    if( !WC()->session->__isset( "reload_checkout" )) {
        /* Gift wrap price */
        $additionalPrice = 5;
        foreach ( $cart_object->cart_contents as $key => $value ) {
            if( isset( $value["embossing_fee"] ) ) {
                $orgPrice = floatval( $value['data']->price );
                                $discPrice = $orgPrice + $additionalPrice;
                $value['data']->set_price($discPrice);
            }
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'calculate_embossing_fee', 99 );

Do anyone know why this would be throwing up an error and how I can resolve it?

The error I get is:
Sure:

Notice: price was called incorrectly. Product properties should not be accessed directly. Backtrace: require('wp-blog-header.php'), require_once('wp-includes/template-loader.php'), include('/themes/bdop/page.php'), the_content, apply_filters('the_content'), WP_Hook->apply_filters, call_user_func_array, do_shortcode, preg_replace_callback, do_shortcode_tag, call_user_func, WC_Shortcodes::cart, WC_Shortcodes::shortcode_wrapper, call_user_func, WC_Shortcode_Cart::output, WC_Cart->calculate_totals, do_action('woocommerce_before_calculate_totals'), WP_Hook->do_action, WP_Hook->apply_filters, call_user_func_array, calculate_embossing_fee, WC_Abstract_Legacy_Product->__get, wc_doing_it_wrong Please see Debugging in WordPress for more information. (This message was added in version 3.0.) in /Applications/MAMP/htdocs/bdop/wp-includes/functions.php on line 4139

1 Answer
1

Well, the problem is you are calling price directly at $value['data']->price. Make it $value['data']->get_price() and I think you problem will be fixed. So the whole code block will be-

function calculate_embossing_fee( $cart_object ) {
    if( !WC()->session->__isset( "reload_checkout" )) {
        /* Gift wrap price */
        $additionalPrice = 5;
        foreach ( $cart_object->cart_contents as $key => $value ) {
            if( isset( $value["embossing_fee"] ) ) {
                // Turn $value['data']->price in to $value['data']->get_price()
                $orgPrice = floatval( $value['data']->get_price() );
                $discPrice = $orgPrice + $additionalPrice;
                $value['data']->set_price($discPrice);
            }
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'calculate_embossing_fee', 99 );

Hope that helps.

Leave a Comment