Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jackbillstrom
Created November 18, 2020 23:08
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 jackbillstrom/80abc1851b7d47979c2b469b90adac28 to your computer and use it in GitHub Desktop.
Save jackbillstrom/80abc1851b7d47979c2b469b90adac28 to your computer and use it in GitHub Desktop.
Woocommerce Ajax Add To Cart Button
<?php
//AJAX ADD TO CART BUTTON
$product_id = 143;
if( !my_custom_cart_contains( $product_id ) ) {
?>
<button class="my-custom-add-to-cart-button" data-product-id="<?php echo $product_id; ?>">add to cart</button>
<?php
} else {
?>
<button class="my-custom-add-to-cart-button" data-product-id="<?php echo $product_id; ?>" disabled="disabled">added to cart</button>
<?php
}
?>
<?php
//ADD TO CART FUNCTION
add_action('wp_footer', 'my_custom_wc_button_script');
function my_custom_wc_button_script() {
?>
<script>
jQuery(document).ready(function($) {
var ajaxurl = "<?php echo esc_attr( admin_url( 'admin-ajax.php' ) ); ?>";
$( document.body).on('click', '.my-custom-add-to-cart-button', function(e) {
e.preventDefault();
var $this = $(this);
if( $this.is(':disabled') ) {
return;
}
var id = $(this).data("product-id");
var data = {
action : 'my_custom_add_to_cart',
product_id : id
};
$.post(ajaxurl, data, function(response) {
if( response.success ) {
$this.text("added to cart");
$this.attr('disabled', 'disabled');
$( document.body ).trigger( 'wc_fragment_refresh' );
}
}, 'json');
})
});
</script>
<?php
}
add_action('wp_ajax_my_custom_add_to_cart', "my_custom_add_to_cart");
add_action('wp_ajax_nopriv_my_custom_add_to_cart', "my_custom_add_to_cart");
function my_custom_add_to_cart() {
$retval = array(
'success' => false,
'message' => ""
);
if( !function_exists( "WC" ) ) {
$retval['message'] = "woocommerce not installed";
} elseif( empty( $_POST['product_id'] ) ) {
$retval['message'] = "no product id provided";
} else {
$product_id = $_POST['product_id'];
if( my_custom_cart_contains( $product_id ) ) {
$retval['message'] = "product already in cart";
} else {
$cart = WC()->cart;
$retval['success'] = $cart->add_to_cart( $product_id );
if( !$retval['success'] ) {
$retval['message'] = "product could not be added to cart";
} else {
$retval['message'] = "product added to cart";
}
}
}
echo json_encode( $retval );
wp_die();
}
function my_custom_cart_contains( $product_id ) {
$cart = WC()->cart;
$cart_items = $cart->get_cart();
if( $cart_items ) {
foreach( $cart_items as $item ) {
$product = $item['data'];
if( $product_id == $product->id ) {
return true;
}
}
}
return false;
}
//Created By Adhersh M Nair
//Reference: https://gist.github.com/gschoppe/46f37a75841738ab86ef3039fc8010e6#file-wc_ajax_add_to_cart-php
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment