在Woocommerce结帐页面,我试图在结帐页面上添加一个复选框
我参考了这些文章
woocommerce custom checkout field to add fee to order ajax
Checkbox field that add / remove a custom fee in WooCommerce的
Add a checkout checkbox field that enable a percentage fee in Woocommerce
add_action( 'woocommerce_review_order_before_order_total', 'checkout_shipping_form_packing_addition', 20 );
function checkout_shipping_form_packing_addition( ){
echo '<tr class="packing-select"><th>';
woocommerce_form_field( 'add_gift_box', array(
'type' => 'checkbox',
'class' => array('add_gift_box form-row-wide'),
'label' => __('Hỗ trợ cài đặt'),
'placeholder' => __(''),
));
echo '</th><td>';}
add_action( 'wp_footer', 'woocommerce_add_gift_box' );
function woocommerce_add_gift_box() {
if (is_checkout()) {
?>
<script type="text/javascript">
jQuery( document ).ready(function( $ ) {
$('#add_gift_box').click(function(){
jQuery('body').trigger('update_checkout');
});
});
</script>
<?php
}}
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );
function woo_add_cart_fee( $cart ){
if ( ! $_POST || ( is_admin() && ! is_ajax() ) ) {
return;
}
if ( isset( $_POST['post_data'] ) ) {
parse_str( $_POST['post_data'], $post_data );
} else {
$post_data = $_POST; // fallback for final checkout (non-ajax)
}
if (isset($post_data['add_gift_box'])) {
$sl = WC()->cart->get_cart_contents_count();
$extracost = 50000 * $sl; // not sure why you used intval($_POST['state']) ?
WC()->cart->add_fee( 'Hỗ trợ cài đặt x '.$sl.'', $extracost );
}}
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( 'add_gift_box' === $key && is_checkout() ) {
$optional = ' <span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
$field = str_replace( $optional, '', $field );
}
return $field;
}
字符串
它不像我想的那样工作。我做错了什么?
任何帮助都很感激。
1条答案
按热度按时间svujldwt1#
你真的需要使用Wordpress Ajax和WC_sessions来让它像 ”Add a checkout checkbox field that enable a percentage fee in Woocommerce“ 回答线程一样工作。
下面是你重新访问的代码:
字符串
代码在您的活动子主题(或活动主题)的functions.php文件中。在Woocommerce版本3.6.5上测试并使用Storefront主题。