type:
snippet
category:
Misc cart and checkout
name:
Creating an Add To Cart link based on an existing cart session
versions:
0.7.0, 0.7.1, 0.7.2, 1.0
reference:
https://forum.foxycart.com/discussion/6133/starting-new-cart-sessions/p1
tags:
cart, checkout, addtocart, link

Currently FoxyCart doesn't have a built in method for passing sessions between customers - this script can allow you to setup a function which creates a single add to cart link based on the current cart contents. This script takes the current cart contents, loops through it all, and creates an add to cart link. This is only part of the puzzle - you'll need to work out how this integrates into your setup.

This script was originally developed to allow a merchant to fill out a cart and then pass the cart session over to a customer using an add to cart link.

Javascript

<script type="text/javascript">
  var baseNames = ["name", "code", "image", "url", "quantity", "quantity_min", "quantity_max", "price", "weight", "shipto", "category", "sub_frequency"];
  var subNames = ["sub_startdate", "sub_nextdate", "sub_enddate"];
  var storeDomain = "store.foxycart.com";
  var checkout = true;
  var empty = true;
 
  var atc = [];
  i = 1;
  for (var p in fc_json.products) {
    var product = fc_json.products[p];
    for (var attr in product) {
      if (product[attr] != "") {
        if (jQuery.inArray(attr, baseNames) > -1) {
          atc.push(i + ":" + attr + "=" + product[attr]);
        } else if (jQuery.inArray(attr, subNames) > -1 && product[attr] != "0000-00-00") {
          atc.push(i + ":" + attr + "=" + product[attr]);
        } else if (attr == "options") {
          for (var opt in product[attr]) {
            atc.push(i + ":" + opt + "=" + product[attr][opt]);
          }
        }
      }
    }
    i++;
  }
 
  for (var c in fc_json.custom_fields) {
    atc.push("h:" + c + "=" + fc_json.custom_fields[c]);
  }
 
  if (fc_json.hasOwnProperty("coupons")) {
    for (var coupon in fc_json.coupons) {
      atc.push("coupon=" + coupon);
    }
  }
 
  var cart_link = "https://" + storeDomain + "/cart?";
      cart_link += (checkout) ? "cart=checkout&" : "";
      cart_link += (empty) ? "empty=true&" : "";
      cart_link += atc.join("&");
</script>

Known issues

Only a single coupon will be included in the add to cart link - even if more coupons are included in the cart session

Site Tools