I have this button:
<a href="http://my-site/checkout/" target="_blank" class="dt-sc-button">bla bla</a>
This button is located on my homebage and is generated by a page builder. What I want to accomplish is when somebody click on the button, it will take them on the checkout, and add a product to the cart. I know that this can be accomplished via a URL, but I need to have this button do other things as well(client idea).
So right now I’m stucked here:
JQuery
jQuery(document).ready(function($){
$(".remove-all").click(function(){
$.ajax({
url: "wp-admin/admin-ajax.php",
data: 'myajax'
});
});
});
PHP
add_action('wp_ajax_myajax', 'myajax');
add_action('wp_ajax_nopriv_myajax', 'myajax');
function myajax() {
global $woocommerce;
$product_id = 264;
$woocommerce->cart->add_to_cart($product_id);
die();
}
I’m a javascript noob, so can you please point me to the right direction, or maybe give me a hint on what I’m doing wrong.
Thanks in advance!
As I mentioned in the comments, you can pretty much borrow from core WooCommerce functions.
First, here’s the button we’ll be trying to ajaxify:
Secondly, we’ll load our custom script and pass it important variables such as the admin ajax and checkout urls.
Now we will write our ajax callbacks, which is copied almost verbatim from WooCommerce core with only a few small modifications:
And finally the contents of
test.js
:You likely need to cancel/prevent the default action of clicking the link, and then redirect once the AJAX call finishes (this is just one way to do it):
PHP