Skip to content

Instantly share code, notes, and snippets.

@heldervilela
Last active May 4, 2023 08:39
Show Gist options
  • Save heldervilela/4d1fac4d7e9c1cbf7af56656a1f0db8b to your computer and use it in GitHub Desktop.
Save heldervilela/4d1fac4d7e9c1cbf7af56656a1f0db8b to your computer and use it in GitHub Desktop.
woocommerce custom checkout field to add fee to order ajax
<?php
/**
* Add html
*
* @version 1.0.0
* @since 1.0.0
*/
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' => esc_html__( 'Gift Box + 1€', '@@pkg.textdomain' ),
'placeholder' => '',
), $checkout->get_value( 'add_gift_box' ));
echo '</div>';
}
/**
* Add Javascript
*
* @version 1.0.0
* @since 1.0.0
*/
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 fee to cart
*
* @link https://docs.woocommerce.com/document/add-a-surcharge-to-cart-and-checkout-uses-fees-api/
* @version 1.0.0
* @since 1.0.0
*/
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;
}
if (isset($post_data['add_gift_box'])) {
$extracost = 1;
WC()->cart->add_fee( esc_html__( 'Gift Box:', '@@pkg.textdomain' ), $extracost );
}
}
@EyalAlfasi
Copy link

Hi, how can I inject the received data (checked or not) to the thankyou page and the emails?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment