Created
June 23, 2021 19:41
-
-
Save mortenebak/fde35ba7607038c8f53b8f72f5a7700d to your computer and use it in GitHub Desktop.
Dynamic Fee @ WooCommerce Checkout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // Part 1 | |
| // Display Radio Buttons | |
| add_action( 'woocommerce_review_order_before_payment', 'bbloomer_checkout_radio_choice' ); | |
| function bbloomer_checkout_radio_choice() { | |
| $chosen = WC()->session->get( 'radio_chosen' ); | |
| $chosen = empty( $chosen ) ? WC()->checkout->get_value( 'radio_choice' ) : $chosen; | |
| $chosen = empty( $chosen ) ? '0' : $chosen; | |
| $args = array( | |
| 'type' => 'radio', | |
| 'class' => array( 'form-row-wide', 'update_totals_on_change' ), | |
| 'options' => array( | |
| '0' => 'Nej, tak.', | |
| '8' => 'Ja tak, (DKK 10)', | |
| ), | |
| 'default' => $chosen | |
| ); | |
| echo '<div id="checkout-radio" style="border: 1px dotted black; padding: 15px;">'; | |
| echo '<h3>Gaveindpakning?</h3>'; | |
| woocommerce_form_field( 'radio_choice', $args, $chosen ); | |
| echo '</div>'; | |
| } | |
| // Part 2 | |
| // Add Fee and Calculate Total | |
| add_action( 'woocommerce_cart_calculate_fees', 'bbloomer_checkout_radio_choice_fee', 20, 1 ); | |
| function bbloomer_checkout_radio_choice_fee( $cart ) { | |
| if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; | |
| $radio = WC()->session->get( 'radio_chosen' ); | |
| if ( $radio ) { | |
| $cart->add_fee( 'Gaveindpakning', $radio, true, '' ); | |
| } | |
| } | |
| // Part 3 | |
| // Add Radio Choice to Session | |
| add_action( 'woocommerce_checkout_update_order_review', 'bbloomer_checkout_radio_choice_set_session' ); | |
| function bbloomer_checkout_radio_choice_set_session( $posted_data ) { | |
| parse_str( $posted_data, $output ); | |
| if ( isset( $output['radio_choice'] ) ){ | |
| WC()->session->set( 'radio_chosen', $output['radio_choice'] ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment