• Hi everyone,

    I’m new to WordPress and Woocommerce, and I’m trying to add an item to the shopping cart with a button click, using ajax. So I have this code in php:

    function add_product_to_cart() {
        $product_id = 5;
    	$found = false;
    
    	//check if product already in cart
    
    	if (sizeof( WC()->cart->get_cart() ) > 0) {
    	    foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
    		    $_product = $values['data'];
    
    			if ($_product->id == $product_id) {
    			    $found = true;
    				echo "found";
    			}
    		}
    
    		if (!$found) {
    		    WC()->cart->add_to_cart( $product_id );
    			echo "added";
    		}
    	} 
    
    	else {
    	    WC()->cart->add_to_cart( $product_id );
    		echo "added";
    	}
    }

    The problem is that I cannot simply invoke it using ajax, since WC function is undefined. How do I do it then?

    Thanks.

    https://wordpress.org/plugins/woocommerce/

Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
  • The topic ‘Adding product to cart using ajax’ is closed to new replies.