WC()->cart and functions.php

I get this error when adding this code to functions.php

Fatal error: Call to a member function calculate_totals() on a non-object

Read More

This is the code generating the error

WC()->cart->calculate_totals();
WC()->cart->calculate_shipping();
$packages = WC()->shipping->get_packages();

However when i put this code in header.php & footer.php no error and $packages array is returned.

How do i solve this, i need this code in functions.php?

Related posts

Leave a Reply

1 comment

  1. You can do this by simply using init hook in functions.php:

    add_action( 'init', 'get_packages_custom' );
    
    function get_packages_custom() {
       WC()->cart->calculate_totals();
       WC()->cart->calculate_shipping();
       $packages = WC()->shipping->get_packages();
    }