Checkout Block custom fee checkbox

// Register Checkout Field
add_action( 'woocommerce_init', function() {

	if( ! function_exists( 'woocommerce_register_additional_checkout_field' ) ) {
		return;
	}

	woocommerce_register_additional_checkout_field(
		[
			'id' => 'ccom/custom_fee',
			'label' => 'Custom Fee +5%',
			'type' => 'checkbox',
			'location' => 'order',
			'required' => false,
		]
	);

} );

// Repopulate Field Value
add_filter(
	'woocommerce_get_default_value_for_ccom/custom_fee',
	function( $value, $group, $wc_object ) {
	if( WC()->session && WC()->session->get( 'ccom_custom_fee' ) ) {
		return WC()->session->get( 'ccom_custom_fee' );
	}
	return $value;
}, 10, 3 );

// AJAX To Process Field Dynamically
add_action( 'wp_footer', function() {

	if( ! is_checkout() ) {
		return;
	}

	?>
	<script type="text/javascript">

	document.addEventListener( 'DOMContentLoaded', function() {

		document.body.addEventListener( 'change', function( event ) {

			if( ! event.target || event.target.id !== 'order-ccom-custom_fee' ) {
				return;
			}

			if( ! window.wp || ! window.wp.data || ! window.wp.data.dispatch ) {
				return;
			}

			let checkbox = document.getElementById( 'order-ccom-custom_fee' );

			fetch( '/wp-json/ccom/v1/custom_fee', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
					'X-WP-Nonce': "<?php echo wp_create_nonce( 'wp_rest' ); ?>"
				},
				body: JSON.stringify( {
					apply: checkbox.checked
				} )
			} )
				.then( response => response.json() )
				.then( data => {
					if( data.success ) {
						const event = new CustomEvent( 'wc-blocks_added_to_cart' );
						document.body.dispatchEvent( event );
					}
				} )
				.catch( error => console.error( 'Error modifying cart fee:', error )
			);

		} );

	} );

	</script>
	<?php

} );

// Fee Line Item On Cart
add_action( 'woocommerce_cart_calculate_fees', function( $cart ) {

	if( is_admin() && ! defined( 'DOING_AJAX' ) ) {
		return;
	}

	$ccom_custom_fee = WC()->session->get( 'ccom_custom_fee' );

	if( $ccom_custom_fee ) {
		$cart->add_fee(
			'Custom Fee',
			(float) $cart->get_subtotal() * 0.05,
			false
		);
	}

} );

// REST API Endpoint
add_action( 'rest_api_init', function() {

    register_rest_route( 'ccom/v1', '/custom_fee', [

        'methods' => 'POST',
        'callback' => function( $request ) {

			$params = $request->get_json_params();
			$status = isset( $params['apply'] ) ? (bool) $params['apply'] : false;

			if( function_exists('WC') && null === WC()->session ) {
				WC()->frontend_includes();
				if( function_exists( 'wc_load_cart' ) ) {
					wc_load_cart();
				} else {
					WC()->session = new WC_Session_Handler;
					WC()->session->init();
				}
			}

			if( WC()->session ) {
				WC()->session->set( 'ccom_custom_fee', $status );
				WC()->cart->calculate_totals();
				return new WP_REST_Response(
					[ 'success' => true, 'fee_applied' => $status ],
					200
				);
			}

			return new WP_REST_Response( [ 'success' => false ], 400 );
		},
        'permission_callback' => '__return_true',

    ] );

} );

Instructions for Checkout Block custom fee checkbox

  1. Log into a staging or locally hosted clone of your site.
  2. Install and activate Code Snippets plugin.
  3. WP Admin > Snippets > Add New
  4. Copy and paste the code from the section above.
  5. Check to ensure formatting came over properly.
  6. Customize the code as desired.
  7. Add a meaningful title.
  8. Select whether to run on front-end or back-end (or both).
  9. Click “Save and Activate”.
  10. Test your site to ensure it works.
  11. Disable if any problems, or recover.
  12. Repeat for live environment.

Need help modifying Checkout Block custom fee checkbox?

Contact me. I can help with fitting projects or refer to my partner.

License

All code snippets are licensed GPLv2 (or later) matching WordPress licensing.

Except when otherwise stated in writing the copyright holders and/or other parties provide the program as-is without warranty of any kind, either expressed or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose.

Disclaimer of warranty