WooCommerce cannot access cart from product class

2019-05-07 00:48发布

I have a custom WooComerce product type, and I need to access the cart url from within 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 can possibily be wrong?

Is the $woocommerce variable not available when defining a custom product class?

If so, is there some internal method / variable to access it? (Or the cart specifically?)

1条回答
Lonely孤独者°
2楼-- · 2019-05-07 01:39

Updated for WC 3+

Using $woocommerce->cart = new WC_Cart(); to create a new object instance is an apparently the solution to avoid 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();     
    }
}
查看更多
登录 后发表回答