// Display the custom checkbow field in checkout
add_action( 'woocommerce_after_order_notes', 'fee_installment_checkbox_field', 20 );
function fee_installment_checkbox_field(){
	echo '<tr class="packing-select"><th>';

	woocommerce_form_field( 'extra_bezorgkosten', array(
		'type'          => 'checkbox',
		'class'         => array('bezorgkosten form-row-wide'),
		'label'         => __('Mijn afleveradres is op de eerste verdieping (of hoger) en alleen bereikbaar met de trap. (Er wordt € 35,- extra in rekening gebracht voor uw bestelling)'),
		'placeholder'   => __(''),
	), WC()->session->get('extra_bezorgkosten') ? '1' : '' );

	echo '</th><td>';
}

// jQuery - Ajax script
add_action( 'wp_footer', 'checkout_fee_script' );
function checkout_fee_script() {
	// Only on Checkout
	if( is_checkout() && ! is_wc_endpoint_url() ) :

	if( WC()->session->__isset('extra_bezorgkosten') )
		WC()->session->__unset('extra_bezorgkosten')
	?>
	<script type="text/javascript">
	jQuery( function($){
		if (typeof wc_checkout_params === 'undefined')
			return false;

		$('form.checkout').on('change', 'input[name=extra_bezorgkosten]', function(){
			var fee = $(this).prop('checked') === true ? '1' : '';

			$.ajax({
				type: 'POST',
				url: wc_checkout_params.ajax_url,
				data: {
					'action': 'extra_bezorgkosten',
					'extra_bezorgkosten': fee,
				},
				success: function (result) {
					$('body').trigger('update_checkout');
				},
			});
		});
	});
	</script>
	<?php
	endif;
}

// Get Ajax request and saving to WC session
add_action( 'wp_ajax_extra_bezorgkosten', 'get_extra_bezorgkosten' );
add_action( 'wp_ajax_nopriv_extra_bezorgkosten', 'get_extra_bezorgkosten' );
function get_extra_bezorgkosten() {
	if ( isset($_POST['extra_bezorgkosten']) ) {
		WC()->session->set('extra_bezorgkosten', ($_POST['extra_bezorgkosten'] ? true : false) );
	}
	die();
}


// Add a custom calculated fee conditionally
add_action( 'woocommerce_cart_calculate_fees', 'set_extra_bezorgkosten' );
function set_extra_bezorgkosten( $cart ){
	if ( is_admin() && ! defined('DOING_AJAX') || ! is_checkout() )
		return;

	if ( did_action('woocommerce_cart_calculate_fees') >= 2 )
		return;

	if ( 1 == WC()->session->get('extra_bezorgkosten') ) {
		$items_count = WC()->cart->get_cart_contents_count();
		$fee_label   = sprintf( __( "Extra bezorgkosten" ), '&times;', $items_count );
		$fee_amount  = '35';
		WC()->cart->add_fee( $fee_label, $fee_amount );
	}
}

add_filter( 'woocommerce_form_field' , 'remove_optional_txt_from_installment_checkbox', 10, 4 );
function remove_optional_txt_from_installment_checkbox( $field, $key, $args, $value ) {
	// Only on checkout page for Order notes field
	if( 'extra_bezorgkosten' === $key && is_checkout() ) {
		$optional = '&nbsp;<span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
		$field = str_replace( $optional, '', $field );
	}
	return $field;
}
Geef een reactie 0