WooCommerce cannot access cart from product class

I have a custom product type WooComerce and I need to access the cart url from it.

It would seem simple enough:

class WC_Product_My_Product extends WC_Product_Simple {

 public function some_method() {
  global $woocommerce; 
  $href = $woocommerce->cart->get_cart_url();     
 }
}

However:

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

What could be wrong?

Is the variable $woocommerceunavailable when defining a custom product class?

If so, is there any internal method / variable to access it? (Or a trolley?)

+4
source share
1 answer

Updated for WC 3+

Using $woocommerce->cart = new WC_Cart();to instantiate a new object is apparently a solution to avoid the error:

class WC_Product_My_Product extends WC_Product_Simple {

    public function some_method() {
        WC()->cart = new WC_Cart();
        $href = WC()->cart->get_cart_url();     
    }
}
+3

All Articles