Skip to content

Instantly share code, notes, and snippets.

@mircian
Created September 29, 2018 12:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mircian/709f93862edad5111e36b21c83c27b73 to your computer and use it in GitHub Desktop.
Save mircian/709f93862edad5111e36b21c83c27b73 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.
<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