add product automatically to cart when a customer visits

Highlighted
New Member
6 0 0

HI 

i want to add product automatically in cart when a customer visits the store .. i had this code but it only adds the varient of product. but I also want to add the product which does not have varient. can someone help me out??

Thanks in advance

<script> Shopify = Shopify || {};
Shopify.cart = {{ cart | json }};
if(Shopify.cart !=='undefined'
&& Shopify.cart.items.length === 0){
jQuery.post('/cart/add.js', {
quantity: 1,
id: 1152084600, //put your varian id here (should valid id, if not your site will be reload with nonstop loop)
}).always(function(data){
//window.location.reload(); //if you want to reload page
window.location.href="cart?backurl="+window.location.href; //if you want redirect to cart page
});
}
</script>

0 Likes
Highlighted
Excursionist
21 3 5

with attribute id , 1152084600 write product.first.id

0 Likes
Highlighted
Shopify Partner
13 2 1

All products have at least 1 variant, it's just not obvious in the admin. If you go to your product page (on the front end of the site) and then add .json to the end of the product handle in the URL, it will show you the product JSON and within the "variants" array there will be a variant. You can get the variant ID from there. I'll attach a screenshot of what it should look like. Mine will look a little more structured because I use the JSONView chrome extension, but you'll still have all similar information.

Screen Shot 2020-11-08 at 11.24.19 AM.png

Sam Webb
https://samthewebb.com
sam@samthewebb.com
0 Likes
Highlighted
New Member
6 0 0

Your reply is appreciated but brother I want to add a product which does not have a variant. 

Product with variants goes good but product without variants doesn't work.

Thanks.

0 Likes
Highlighted
Shopify Partner
13 2 1

ALL products have at least one variant, but for products where you didn't explicitly create variants it's not easily visible in the Shopify admin. Add ".json" to the end of your product URL and you'll see that it has a variant, and you can copy that variant's ID, add it to your code and it should add it to cart.

Products are only ever added to cart using a variant ID, so on Shopify's end every single product is always assigned at least one variant. Btw, you can add ".json" either to the end of your front end product page or the product page that's within the admin. Either way it will work to allow you to find the variant ID. The variant will have the title "Default Title".

Sam Webb
https://samthewebb.com
sam@samthewebb.com
0 Likes