WooCommerce-Checkout-Optionsschaltflächen, die eine prozentuale Gebühr basierend auf der Zwischensumme bestimmter Artikel festlegen

Lesezeit: 4 Minuten

Benutzer-Avatar
Rosalito Udtohan

Ich versuche, die Garantieoption in die Woocommerce-Kaufabwicklung zu implementieren. Der folgende Code funktioniert für statische Preiswerte.

// Part 1 - Display Radio Buttons
add_action( 'woocommerce_review_order_before_payment', 'custom_checkout_radio_choice' );
function custom_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' => '1 Year Repair or Replace Warranty - Included',
            '75' => '2 Years Extended Warranty ($75.00)',
            '112.5' => '3 Years Extended Warranty ($112.50)',
        ),
        'default' => $chosen
    );
     
    echo '<div id="checkout-radio">';
    echo '<h4>Choose your Warranty</h4>';
    woocommerce_form_field( 'radio_choice', $args, $chosen );
    echo '</div><br>';  
}
  
// Part 2 - Add Fee and Calculate Total 
add_action( 'woocommerce_cart_calculate_fees', 'custom_checkout_radio_choice_fee', 20, 1 );
function custom_checkout_radio_choice_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    
    $radio = WC()->session->get( 'radio_chosen' );
     
    if ( $radio ) {
        $cart->add_fee( 'Warranty Option', $radio );
    }
}
  
// Part 3 - Add Radio Choice to Session
add_action( 'woocommerce_checkout_update_order_review', 'custom_checkout_radio_choice_set_session' );
function custom_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'] );
    }
}

Bildschirmfoto

Gibt es eine Möglichkeit, die berechneten Garantiebetragsoptionen basierend auf dem prozentualen Zwischensummenbetrag der Artikel auszugeben? Wie:

  • Der Preis für 2 Jahre Garantie beträgt 10 % des Zwischensummenpreises.
  • Die 3-Jahres-Garantie beträgt 15 %. Beispiel:

Wenn die Zwischensumme beispielsweise 85 $ beträgt, wären die anzuzeigenden Garantieoptionen:

  • 2 Jahre Garantieverlängerung (8,50 $) /* 10 % */
  • 3 Jahre Garantieverlängerung (12,75 $) /* 15 % */

OPTIONAL: Ich versuche auch, diese Funktion für ein bestimmtes Produkt oder eine Reihe von Produkten und nicht für alle Produkte zu verwenden. Wenn es eine Möglichkeit gibt, dies einzustellen.

Benutzer-Avatar
LoicTheAztec

Verwenden Sie den folgenden überarbeiteten Code, um eine benutzerdefinierte prozentuale Gebühr basierend auf der Zwischensumme bestimmter Einkaufswagenartikel (für einen definierten Satz von Produkt-IDs) und einem Optionsfeld (prozentuale Garantieauswahl) zu erhalten:

// Custom function to get related cart items subtotal for specific defined product Ids
function get_related_items_subtotal( $cart ) {
    // HERE below define the related targeted products IDs in the array
    $targeted_ids = array(29, 27, 28, 72, 84, 95);
    $custom_subtotal = 0; // Initialize

    // Loop through cart items
    foreach ( $cart->get_cart() as $item ) {
        if ( array_intersect($targeted_ids, array($item['product_id'], $item['variation_id']) ) ) {
            $custom_subtotal += $item['line_subtotal'] + $item['line_subtotal_tax'];
        }
    }
    return $custom_subtotal;
}

// 1 - Display custom checkout radio buttons fields
add_action( 'woocommerce_review_order_before_payment', 'display_custom_checkout_radio_buttons' );
function display_custom_checkout_radio_buttons() {
    $custom_subtotal = get_related_items_subtotal( WC()->cart );

    if ( $custom_subtotal > 0 ) {
        $value = WC()->session->get( 'warranty' );
        $value = empty( $value ) ? WC()->checkout->get_value( 'warranty' ) : $value;
        $value = empty( $value ) ? '0' : $value;

        echo '<div id="checkout-radio">
            <h4>' . __("Choose your Warranty") .'</h4>';

        woocommerce_form_field( 'warranty', array(
            'type' => 'radio',
            'class' => array( 'form-row-wide', 'update_totals_on_change' ),
            'options' => array(
                '0'  => __( '1 Year Repair or Replace Warranty - Included', 'woocommerce' ),
                '10' => __( '2 Years Extended Warranty', 'woocommerce' ) . ' (' . strip_tags( wc_price( 10 * $custom_subtotal / 100 ) ) . ')',
                '15' => __( '3 Years Extended Warranty', 'woocommerce' ) . ' (' . strip_tags( wc_price( 15 * $custom_subtotal / 100 ) ) . ')',
            ),
        ), $value );

        echo '</div>';
    }


}

// 2 - Customizing Woocommerce checkout radio form field
add_filter( 'woocommerce_form_field_radio', 'custom_form_field_radio', 20, 4 );
function custom_form_field_radio( $field, $key, $args, $value ) {
    if ( ! empty( $args['options'] ) && 'warranty' === $key && is_checkout() ) {
        $field = str_replace( '</label><input ', '</label><br><input ', $field );
        $field = str_replace( '<label ', '<label style="display:inline;margin-left:8px;" ', $field );
    }
    return $field;
}

// 3 - Add a percentage Fee based on radio buttons for specific defined product Ids
add_action( 'woocommerce_cart_calculate_fees', 'percentage_fee_based_on_radio_buttons', 20 );
function percentage_fee_based_on_radio_buttons( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $percentage = (float) WC()->session->get( 'warranty' );

    if ( $percentage ) {
        $custom_subtotal = get_related_items_subtotal( $cart );

        if ( $custom_subtotal > 0 ) {
            $label_text = sprintf( __('Extended Warranty %d years', 'woocommerce'), $percentage == 10 ? 2 : 3 );
            $cart->add_fee( $label_text, $custom_subtotal * $percentage / 100 );
        }
    }
}

// 4 - Set chosen radio button value to a WC Session variable
add_action( 'woocommerce_checkout_update_order_review', 'chosen_input_radio_button_value_to_wc_session' );
function chosen_input_radio_button_value_to_wc_session( $posted_data ) {
    parse_str( $posted_data, $fields );

    if ( isset( $fields['warranty'] ) ){
        WC()->session->set( 'warranty', $fields['warranty'] );
    }
}

Der Code wird in die Datei functions.php des aktiven untergeordneten Designs (oder aktiven Designs) eingefügt. Getestet und funktioniert.

  • Wow!, funktioniert wie ein Zauber, aber ein Problem: Wenn ich „2 Jahre erweiterte Garantie“ auswähle, wird in der Bestellzusammenfassung immer noch „erweiterte Garantie 3 Jahre“ angezeigt. Bildschirmfoto: prnt.sc/11sko9p

    – Rosalito Udtohan

    21. April 2021 um 7:56 Uhr

  • @RosalitoUdtohan Aktualisiert… Jetzt wird die richtige Anzahl von Jahren angezeigt, abhängig von der ausgewählten Option.

    – LoicTheAztec

    21. April 2021 um 8:22 Uhr

1046300cookie-checkWooCommerce-Checkout-Optionsschaltflächen, die eine prozentuale Gebühr basierend auf der Zwischensumme bestimmter Artikel festlegen

This website is using cookies to improve the user-friendliness. You agree by using the website further.

Privacy policy