[英]Checkbox field that add / remove a custom fee in WooCommerce
需要根據表單復選框元素向購物車添加自定義費用。 當前基於購物車中產品類別的操作效果很好,並增加了定制送貨費,但客戶可以選擇免費取貨。 是否可以選中交付觸發 WooCommerce 的復選框添加自定義費用操作?
使用來自“對 html 表單上的復選框選中或未選中事件執行操作”的示例 can.change(function) function delivery(id){ if(this.checked) { add_action 用於自定義購物車費用?
add_action( 'woocommerce_cart_calculate_fees', 'add_a_custom_fee', 10, 1 );
function add_a_custom_fee( $cart ) {
$amount = 25;
$cart->add_fee( __('Custom fee'), $amount );
}
選中復選框時,預計自定義購物車費用會出現在購物車中。
以下代碼將在結帳頁面上顯示一個復選框字段,用於啟用/禁用自定義費用:
// Display a checkbox field after billing fields
add_action( 'woocommerce_after_checkout_billing_form', 'add_custom_checkout_checkbox', 20 );
function add_custom_checkout_checkbox(){
woocommerce_form_field( 'custom_fee', array(
'type' => 'checkbox',
'label' => __(' Custom fee'),
'class' => array( 'form-row-wide' ),
), '' );
}
// Remove "(optional)" label on checkbox field
add_filter( 'woocommerce_form_field' , 'remove_order_comments_optional_fields_label', 10, 4 );
function remove_order_comments_optional_fields_label( $field, $key, $args, $value ) {
// Only on checkout page for Order notes field
if( 'custom_fee' === $key && is_checkout() ) {
$optional = ' <span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
$field = str_replace( $optional, '', $field );
}
return $field;
}
// Ajax / jQuery script
add_action( 'wp_footer', 'custom_fee_script' );
function custom_fee_script() {
// On checkoutpage
if( ( is_checkout() && ! is_wc_endpoint_url() ) ) :
?>
<script type="text/javascript">
jQuery( function($){
if (typeof woocommerce_params === 'undefined')
return false;
console.log('defined');
$('input[name=custom_fee]').click( function(){
var fee = $(this).prop('checked') === true ? '1' : '';
$.ajax({
type: 'POST',
url: woocommerce_params.ajax_url,
data: {
'action': 'custom_fee',
'custom_fee': fee,
},
success: function (result) {
$('body').trigger('update_checkout');
console.log(result);
},
});
});
});
</script>
<?php
endif;
}
// Get the ajax request and set value to WC session
add_action( 'wp_ajax_custom_fee', 'get_ajax_custom_fee' );
add_action( 'wp_ajax_nopriv_custom_fee', 'get_ajax_custom_fee' );
function get_ajax_custom_fee() {
if ( isset($_POST['custom_fee']) ) {
WC()->session->set('custom_fee', ($_POST['custom_fee'] ? '1' : '0') );
echo WC()->session->get('custom_fee');
}
die();
}
// Add / Remove a custom fee
add_action( 'woocommerce_cart_calculate_fees', 'add_remove_custom_fee', 10, 1 );
function add_remove_custom_fee( $cart ) {
// Only on checkout
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || is_cart() )
return;
$fee_amount = 25;
if( WC()->session->get('custom_fee') )
$cart->add_fee( __( 'Custom fee', 'woocommerce'), $fee_amount );
}
代碼進入您的活動子主題(或活動主題)的 function.php 文件。 測試和工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.