Skip to content

Instantly share code, notes, and snippets.

@mortenebak
Created June 23, 2021 19:41
Show Gist options
  • Select an option

  • Save mortenebak/fde35ba7607038c8f53b8f72f5a7700d to your computer and use it in GitHub Desktop.

Select an option

Save mortenebak/fde35ba7607038c8f53b8f72f5a7700d to your computer and use it in GitHub Desktop.

Revisions

  1. mortenebak created this gist Jun 23, 2021.
    59 changes: 59 additions & 0 deletions functions.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    <?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'] );
    }
    }