In Woocommerce checkout section, I am trying to add a checkbox that adds an additional product.
I have a working piece of code that adds a fee and updates the cart on click of a checkbox, but I want it to add a product instead of a surcharge fee:
function cart_custom_fee( $cart ) {
if( !$_POST || ( is_admin() && ! is_ajax() ) ) {
return;
}
if( isset( $_POST['post_data'] ) ) {
parse_str( $_POST['post_data'], $post_data );
} else {
$post_data = $_POST;
}
if( isset( $post_data['add_test_item'] ) ) { // This is the checkbox name
WC()->cart->add_fee('Test Item', 35);
}
}
add_action( 'woocommerce_cart_calculate_fees', 'cart_custom_fee' );
This is the code for the checkbox
<script>
jQuery(document).ready(function(){
jQuery('#cp-checkbox').click(function() {
jQuery('body').trigger('update_checkout');
});
});
</script>
And the code works…
Now, I tried changing the code to add a product instead:
function add_item_checkout( $cart ) {
if( !$_POST || ( is_admin() && ! is_ajax() ) ) {
return;
}
if( isset( $_POST['post_data'] ) ) {
parse_str( $_POST['post_data'], $post_data );
} else {
$post_data = $_POST;
}
if( isset( $post_data['add_test_item'] ) ) { // This is the checkbox name
WC()->cart->add_to_cart( 123 ); // 123 is the product ID
}
}
add_action( 'woocommerce_calculate_totals', 'add_item_checkout' );
But it didn't work. Any help will be appreciated.
Update (related to your comment).
This can only be done with Javascript (jQuery) and Ajax as it's a client side event and nothing is submitted when making an action on a checkout field.
When this checkbox will be checked, a specific product will be added to cart refreshing the checkout order review data. If the checkbox is unchecked by the customer, it will remove the specific product, refreshing the checkout order review data.
The code:
Code goes in function.php file of your active child theme (or active theme). Tested and work.
1) The order items and the checkbox custom field under payment methods
2) When enabling the checkbox, the product is added and appear in order items: