François Audras
François Audras

Reputation: 13

Updating cart code for Woocommerce

This PHP code is not working anymore from my backoffice (Slim v2) on www.arneo.vision - under PHP7 with latest WooCommerce version :

global $woocommerce;

var_dump($woocommerce->cart);

$woocommerce->cart->empty_cart();

$woocommerce->cart->add_to_cart( $_GET['product_id']);

var_dump($woocommerce->cart);

How can I update this code to work again? Please help me since I am not a professionnal developer...

Upvotes: 1

Views: 423

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253784

The global $woocommerce; with $woocommerce->cart is replaced by simply WC()->cart

You should also test:

  • If cart is not empty before trying to empty it
  • If $_GET['product_id'] is defined to avoid "Undefined index" error.

So your code should be:

// testing that WC()->cart is defined and it is the front end current live WC_Cart object
if( is_object (WC()->cart ) ):

var_dump(WC()->cart);

if( ! WC()->cart->is_empty() )
    WC()->cart->empty_cart();

if( isset( $_GET['product_id'] ) )
    WC()->cart->add_to_cart( $_GET['product_id'] );

var_dump(WC()->cart);

endif;

Upvotes: 1

Related Questions