Skip to content

Instantly share code, notes, and snippets.

@kostas-artware
Created September 23, 2021 10:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kostas-artware/e4223675b73c379b6da6f4037b83c102 to your computer and use it in GitHub Desktop.
Save kostas-artware/e4223675b73c379b6da6f4037b83c102 to your computer and use it in GitHub Desktop.
Add a checkbox with a fee in woocomerce checkoute page.
add_action( 'woocommerce_after_checkout_billing_form', 'add_box_option_to_checkout' );
function add_box_option_to_checkout( $checkout ) {
echo '<div id="message_fields">';
woocommerce_form_field( 'add_gift_box', array(
'type' => 'checkbox',
'class' => array('add_gift_box form-row-wide'),
'label' => __('Ilość pudełek ozdobnych - 25 PLN/szt'),
'placeholder' => __(''),
), $checkout->get_value( 'add_gift_box' ));
woocommerce_form_field( 'add_gift_box', array(
'type' => 'checkbox',
'class' => array('add_gift_box form-row-wide'),
'label' => __('Ilość pudełek ozdobnych - 25 PLN/szt'),
'placeholder' => __(''),
), $checkout->get_value( 'add_gift_box' ));
echo '</div>';
}
// Update Cart
add_action( 'wp_footer', 'woocommerce_add_gift_box' );
function woocommerce_add_gift_box() {
if (is_checkout()) {
?>
<script type="text/javascript">
jQuery( document ).ready(function( $ ) {
$('#add_gift_box').click(function(){
jQuery('body').trigger('update_checkout');
});
});
</script>
<?php
}
}
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );
function woo_add_cart_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; // fallback for final checkout (non-ajax)
}
if (isset($post_data['add_gift_box'])) {
$extracost = 25; // not sure why you used intval($_POST['state']) ?
WC()->cart->add_fee( 'Ozdobne pudełka:', $extracost );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment