Customizing Buy Button to Add Secondary Product Based on Selected Variant

Highlighted
Tourist
8 0 1

We would like to add an additional product by default if a specific variant is selected. For example: If a customer selects 'Download and CD Option' we would like to add an additional product to the cart.  (This is for the Buy Button channel)

 

I used this code for our store and it works really well. I used the product weight to figure out if it requires shipping and then it applies the product to the cart based on the selection:

{% assign product = all_products['constructioncontracts-cd-option'] %}

{% unless cart.item_count == 0 or product.empty? or product.variants.first.available == false %}
  {% assign variant_id = product.variants.first.id %}

{% unless cart.total_weight == 0 %}

  <script>
  (function($) {
    var cartItems = {{ cart.items | json }},
        qtyInTheCart = 0,
        cartUpdates = {};
    for (var i=0; i<cartItems.length; i++) {
      if ( cartItems[i].id === {{ variant_id }} ) {
        qtyInTheCart = cartItems[i].quantity;
        break;
      }
    }
    if ( ( cartItems.length === 1 ) && ( qtyInTheCart > 0 ) ) {
      cartUpdates = { {{ variant_id }}: 0 }
    }
    else if ( ( cartItems.length >= 1 ) && ( qtyInTheCart !== 1 ) ) {
      cartUpdates = { {{ variant_id }}: 1 }
    }
    else {
      return;
    }
    var params = {
      type: 'POST',
      url: '/cart/update.js',
      data: { updates: cartUpdates },
      dataType: 'json',
      success: function(stuff) { 
        window.location.href = '/cart';
      }
    };
    $.ajax(params);
  })(jQuery);
    
  
  </script>
{% endunless %}
{% endunless %}

Now I'm just trying to figure out how to get the buy button to function in a similar way.

0 Likes
Shopify Partner
19 0 7

Hello IndiaB,

 

Well all you have to do is use the Shopify Ajax API which allows you to POST a variantID and Quantity.

Here is the reference: https://help.shopify.com/en/themes/development/getting-started/using-ajax-api#add-to-cart

 

Just wrote this quickly, may have a couple bugs but at first glance it should work. :) GL

   // create a queue for products to be added in a row
Shopify.queue = [];
Shopify.moveAlong = function() {
if (Shopify.queue.length) {
const request = Shopify.queue.shift();
Shopify.addItem(request.variantId, request.quantity, Shopify.moveAlong);
}
};

// Create complementary function function addComplementaryProduct(variantId, quantity = 1) { Shopify.queue.push({ variantId: variantId, quantity: quantity }); Shopify.moveAlong(); } //Catch Add to cart $(document).on('submit', 'form[action="/cart/add"]:not(.noAJAX)', function(e) { // Prepare the data in order to send it to the Shopify API const $form = $(this); // Serialize the form and post it to the shopify API $.post('/cart/add.js', $form.serialize(), function(data) { // Convert data into JSON const dataJSON = $.parseJSON(data); // Check if the item added needs a complimentary product if (dataJSON.variant_id === '1234567890') { //call the function created earlier with the id and the quantity addComplementaryProduct('1234567890', 5); } }); });
2 Likes
Tourist
8 0 1

@Starshards - Will this work for the Buy Button? We are using the embedded button on our site (outside of Shopify)

0 Likes
Shopify Partner
19 0 7

@IndiaB Sorry but not this is within Shopify's environment. If you're using an embedded Buy Now button it would have to be a custom script which I could write actually or if you use a 3rd party shipping like Ordoro you can create a bundle of 2 products and the Buy Now button adds that bundle.

Do you have the URLs 

0 Likes
Tourist
8 0 1

 @Starshards We're shipping through Shopify.

 

Here's a brief explanation of what I've run into:

 

It all started with the Digital Downloads app. The reason why we're trying to automatically add an additional product is because it creates a 'partially fulfilled' order, because one is the download and the other is the physical CD - thereby allowing us to create a label within Shopify.

 

I've had several people tell me to try SendOwl, which I understand why they would say that; however, I've already set up all of our products using Digital Downloads and we like the breakdown of information better in that app.  (ex: number of downloads, simplified list, etc)

 

Here's the post I submitted concerning this

 

0 Likes
Tourist
8 0 1

@Starshards 

 

This Post on Stack Overflow  Talks about customizing a Buy Button to set a minimum quantity... Which isn't what we want to do, we want to add in the secondary shipping product. It's a little outdated, but it shows that some customization is possible.

 

I'm rather frustrated with it, to be honest. Don't get me wrong - Shopify is fantastic. It just seems like every time I find a solution to one problem, another one occurs. 

0 Likes
Shopify Partner
19 0 7

@IndiaB I just downloaded the app to test it and it seems you are correct this app doesn't work as intended, I'm sure if you ask the developer he can fix that easily for you. In addition, you could change the setting within Shopify to automatically fulfill the orders which would send them the link directly but then you'd have to track what was sent or not with a tag. Not the easiest solution.

 

So instead of a Buy Button, you can create a Permalink.

 

Permalinks are MAGICAL

 

You can preload a cart with as many items as you want, add discounts, preload customers information, and much more.

 

You're going to want to include the VariantID & Quantity for the products you want to add eg:

 

http://yourstore.com/cart/{variant_id}:{quantity},{variant_id}:{quantity}(,...)
http://your-store.myshopify.com/cart/70881412:2,70881382:4

You can also add these parameters:

Checkout parameter Description

checkout[email]Email of the customer making the checkout.
checkout[shipping_address][first_name]Access [first_name].
checkout[shipping_address][last_name]Access [last_name].
checkout[shipping_address][address1]Access [address1].
checkout[shipping_address][address2]Access [address2].
checkout[shipping_address][city]Access [city].
checkout[shipping_address][zip]Access [zip].

 

 

And apply discounts like so:

/cart/{variant_id}:{quantity}?discount={discount_code}

 

So a Buy Now Link with a button style could look something like this:

<style>
// Button like Shopify muahahaha
.btn { display: inline-block; padding: 8px 20px; border-radius: 5px; box-shadow: 0 5px 15px 0 rgba(0,0,0,0.15); background-color: #5b68c6; color: white; font-size: 16px; font-weight: bold; letter-spacing: 0.25px;
transition: 150ms ease; }
.btn:hover {
background-color:#202e78;
} </style> <a href="http://your-store.com/cart/70881412:1" class="btn">Buy this item</a>

I hope that resolves your issue ;)

 

0 Likes
Shopify Partner
19 0 7

@IndiaB I responded but it said my message needed to be approved, basically what I said was, I tested the app, understand your problem better, instead of using a Buy Now Button you can use permalinks which prepopulate a cart and sends the user to the checkout:

http://your-store.com/cart/{variant_id}:{quantity}, {variant_id}:{quantity} (,...)
https://thebedsheetclub.com/cart/13764701749311:1,12231872413759:2
That's my store :)

So you can create a link which looks like a button like this: 

<style>
.btn {
	display: inline-block;
	padding: 8px 20px;
	background-color: #5b68c6;
	font-weight: bold;
	color: white;
	letter-spacing: 0.25px;
	border-radius: 5px;
	box-shadow: 0 5px 15px 0 rgba(0,0,0,0.15);
	font-size: 16px;
	transition: 150ms ease;
}
.btn:hover {
       background-color: #303a8b;
}
</style>

<a href="https://thebedsheetclub.com/cart/13764701749311:1,12231872413759:2" class="btn">Buy this item</a>

 

0 Likes
Tourist
8 0 1

@Starshards This is a great suggestion. 

 

However, we like the way the buy button modal works and looks. It keeps them on our external site and lets them choose their options from the dropdown menu. We have variants for different operating systems (mac or windows) and for the download/CD option as well.  

 

This option was considered, but we only have one page per product (not for the variants) and we'd have to restructure our layout to include a button for each variant if we did that.  

 

I appreciate the help, though! 

0 Likes
Shopify Partner
19 0 7

@IndiaB Well, in that case, it's time to use the Javascript SDK, that'll let you have the same feel on your external website.

You'll be able to add things to your cart according to whatever you wish and have a sidecart.

https://help.shopify.com/en/api/custom-storefronts/js-buy-sdk

 

Depends on which technology you use but you can choose node, or react, and more here are some storefront examples:

https://github.com/Shopify/storefront-api-examples

1 Like