对于想要提供有条件结帐费的人来说,这是一个很棒的WooCommerce代码段(或插件,如果您希望这样称呼)。例如,您可能需要显示自定义结帐单选按钮以选择高级包装类型,礼品包装选项,特定服务或任何可以提高您的AOV(平均订单价值)的商品。
单选按钮的选择必须与“ Ajax”一起使用-这意味着选择了单选按钮后,结帐必须刷新以显示更新的费用和总计。
// 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' => 'No Option',
'10' => 'Option 1 ($10)',
'30' => 'Option 2 ($30)',
),
'default' => $chosen
);
echo '<div id="checkout-radio">';
echo '<h3>Customize Your Order!</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( 'Option Fee', $radio );
}
}
// 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'] );
}
}