Skip to content

Instantly share code, notes, and snippets.

@michelve
Created September 14, 2016 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michelve/9bb4987b5ea0c1d04bb039fc88aefd38 to your computer and use it in GitHub Desktop.
Save michelve/9bb4987b5ea0c1d04bb039fc88aefd38 to your computer and use it in GitHub Desktop.
AJAX add to cart - woocommerce
<a id="buy" href="#">Buy this!</a>
<script>
$('#buy').click(function(e) {
e.preventDefault();
addToCart(19);
return false;
});
function addToCart(p_id) {
$.get('/wp/?post_type=product&add-to-cart=' + p_id, function() {
// call back
});
}
</script>
<?php
// Add item to cart on visit
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
// select ID
$product_id = 851;
//check if product already in cart
if ( WC()->cart->get_cart_contents_count() == 0 ) {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
}
?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment