Created
September 14, 2016 12:41
-
-
Save michelve/9bb4987b5ea0c1d04bb039fc88aefd38 to your computer and use it in GitHub Desktop.
AJAX add to cart - woocommerce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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