I managed to achieve what I wanted, here is how:
Add this PHP code (maybe in the functions.php of your child theme)
function load_addtocart_button() {
$price = $_POST['price'];
$qty = $_POST['qty'];
$result = do_shortcode('[wp_cart_button name="Test Product ('.$qty.' units)" price="'.$price.'"]');
wp_send_json( $result );
}
add_action('wp_ajax_load_addtocart_button', 'load_addtocart_button');
add_action('wp_ajax_nopriv_load_addtocart_button', 'load_addtocart_button');
in your page add an HTML bloc with a code similar to this :
<div id="addtocart_container"></div>
<script type="application/javascript">
function calculate(qty) {
let unit_price;
if (qty < 260) {
unit_price = 0;
}
else if (qty >= 260 && qty < 500) {
unit_price = 1.07;
}
else if (qty >= 500 && qty < 1000) {
unit_price = 0.77;
}
else if (qty >= 1000 && qty < 2000) {
unit_price = 0.72;
}
else if (qty >= 2000 && qty < 5000) {
unit_price = 0.69;
}
else if (qty >= 5000 && qty < 10000) {
unit_price = 0.63;
}
else {
unit_price = 0.57;
}
return (qty*unit_price).toFixed(2);
}
(function($) {
$('#form-field-price').prop('readonly', true);
$('#form-field-qty').on('change', function() {
let qty = $(this).val();
let price = calculate(qty);
let ajaxurl = window.location.protocol + '//' + window.location.hostname + '/wp-admin/admin-ajax.php';
$('#form-field-price').val(price);
if (price > 0) {
$.post({
url: ajaxurl,
data: {
action: 'load_addtocart_button',
qty: qty,
price: price,
},
success: function(data) {
let $container = $('#addtocart_container');
$container.html(data);
$container.find('[name="_wp_http_referer"]').val(window.location.pathname);
$container.find('[name="cartLink"]').val(window.location.href);
}
});
}
});
})(jQuery);
</script>
The “Add to cart” button will be displayed in your div container with every needed parameter.
Feel free to modify or ask if you have any question
-
This reply was modified 4 years ago by th3bish0p.