How To Add Products To Cart Programatically In Prestashop

Using the code which will be provided in this tutorial you will be able to add products to cart progrmatically. To achive this functionality you need to know the product id and attributes id, anyway I will show you how to get them too. id_product_attribute is the attribute of the product if any is available, this tutorial will assume you already have some attributes for your products.

public function createNewCart($id_product, $id_product_attribute){
    $cart = $this->context->cart;
      $cart->id_lang = (int)$this->context->cookie->id_lang;
      $cart->id_currency = (int)$this->context->cookie->id_currency;
      $cart->id_customer  = (int)$this->context->customer->id;
      $cart->id_shop_group = (int)$this->context->shop->id_shop_group;
      $cart->id_shop = $this->context->shop->id;
    $cart->add();
    $this->context->cookie->id_cart = (int)($cart->id);    
    	$cart->update();
    $cart->updateQty(1, (int)$id_product, (int)$id_product_attribute, false);
    if($this->context->cookie->id_cart != 0 && !empty($this->context->cookie->id_cart)){
      return true;
    }
  }

The above function will add the product with the id provided by you in the cart, as you can see we need to add few details in cart object in order to make it work. The function which actually add the products to the cart is updateQty() where we ask to update quantity with our product.

Now, the achive the above function we need one more fields (attribute id), to get this id we need to do the following steps:

  1. get product we need using its id
  2. get combinations from the product
  3. get attribute id

To get product by its id we will use the following function:

$product = new Product($product_id);

Now, once we have the product we can grab the combinations of the product using the following function:

$combinations=$product->getAttributeCombinations($this->context->language->id);

Now we can get the id_product_attribute from the combinations array. This is one of the methods though which you can add products to cart programatically in prestashop, let me know if it worked for you. 

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x