amritansh
9/26/2017 - 5:45 AM

This function add a product into the woocommerce cart

This function add a product into the woocommerce cart

add_product_to_cart($product_id, $quantity, $variation_id, $variation, $cart_item_data);

function add_product_to_cart($product_id, $default_product_quantity, $variation_id, $variation = array(), $cart_item_data = array()) {
//check if product already in cart
    if (sizeof(WC()->cart->get_cart()) > 0) {
        WC()->session->set("cart_strorage", WC()->cart->get_cart());
        foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
            $_product = $values['data'];
            if ($_product->id == $product_id) {
                $found = true;
                $result['product_id'] = $product_id;
                $result['status'] = 'already_added';
                $result['hash_key'] = $cart_item_key;
                $_SESSION['result'] = $result;
                $has_subscription = TRUE;
            } else {
                WC()->cart->remove_cart_item($cart_item_key);
            }
        }
        if (!$has_subscription) {
            $result['hash_key'] = WC()->cart->add_to_cart($product_id, $default_product_quantity, $variation, $cart_item_data);
            $result['product_id'] = $product_id;
            $result['status'] = 'fresh';
            $_SESSION['result'] = $result;
        }
    } else {
// if no products in cart, add it
        $result['hash_key'] = WC()->cart->add_to_cart($product_id, $default_product_quantity, $variation, $cart_item_data);
        $result['product_id'] = $product_id;
        $result['status'] = 'fresh';
        $_SESSION['result'] = $result;
    }
}