-
-
Save Sanabria/dcb948d1ad262053a7285b4183778571 to your computer and use it in GitHub Desktop.
Create a simple function which you can globally call to easily add a product to the cart by id.
This file contains hidden or 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
<script type="text/javascript"> | |
function m_wc_add_to_cart( product_id ) { | |
if ( 'undefined' === typeof wc_add_to_cart_params ) { | |
// The add to cart params are not present. | |
return false; | |
} | |
var data = { | |
product_id: product_id, | |
quantity: 1, | |
}; | |
jQuery.post( wc_add_to_cart_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'add_to_cart' ), data, function( response ) { | |
if ( ! response ) { | |
return; | |
} | |
// This redirects the user to the product url if for example options are needed ( in a variable product ). | |
// You can remove this if it's not the case. | |
if ( response.error && response.product_url ) { | |
window.location = response.product_url; | |
return; | |
} | |
// Remove this if you never want this action redirect. | |
if ( wc_add_to_cart_params.cart_redirect_after_add === 'yes' ) { | |
window.location = wc_add_to_cart_params.cart_url; | |
return; | |
} | |
// This is important so your theme gets a chance to update the cart quantity for example, but can be removed if not needed. | |
jQuery( document.body ).trigger( 'added_to_cart', [ response.fragments, response.cart_hash ] ); | |
}); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment