Last active
January 11, 2022 22:56
-
-
Save willybahuaud/23155c6b48fafefd4322605dd5edf7cc to your computer and use it in GitHub Desktop.
add shipping warranty fees
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_action( 'woocommerce_review_order_after_shipping', 'shipping_warranty_cb' ); | |
function shipping_warranty_cb() { | |
?><tr class="shipping-fee"> | |
<th><?php _e( 'Assurance Expédition' ); ?></th> | |
<td><?php | |
woocommerce_form_field( 'shipping_warranty', array( | |
'type' => 'checkbox', | |
'class' => array('checkbox_field'), | |
'id' => 'shipping_warranty', | |
'label' => __('Souscrire à la garantie livraison' ), | |
'required' => false, | |
), WC()->session->get('shipping_warranty')); | |
?></td> | |
</tr><?php | |
} | |
add_filter( 'woocommerce_cart_calculate_fees', 'add_shhipping_warranty_fees', 10, 1 ); | |
function add_shhipping_warranty_fees( $cart ) { | |
if( WC()->session->get('shipping_warranty') ) { | |
$amount = 10; // pour 10 € | |
$cart->add_fee( __( 'Assurance expédition' ), $amount ); | |
} | |
} | |
add_action( 'wp_ajax_save_shipping_warranty', 'w_save_shipping_warranty' ); | |
add_action( 'wp_ajax_nopriv_save_shipping_warranty', 'w_save_shipping_warranty' ); | |
function w_save_shipping_warranty() { | |
$shipping_warranty = ! empty( $_POST['shipping_warranty'] ); | |
WC()->session->set('shipping_warranty', $shipping_warranty ); | |
wp_send_json_success(); | |
} | |
add_action( 'wp_footer', 'w_shipping_warranty_script' ); | |
function w_shipping_warranty_script() { | |
if ( is_checkout()) : | |
?> | |
<script type="text/javascript"> | |
jQuery( function($){ | |
$('form.checkout').on('change', 'input[name="shipping_warranty"]', function(){ | |
$.ajax({ | |
type: 'POST', | |
url: wc_checkout_params.ajax_url, | |
data: { | |
'action': 'save_shipping_warranty', | |
'shipping_warranty': $('#shipping_warranty:checked').val(), | |
}, | |
success:function() { | |
$(document.body).trigger('update_checkout'); | |
} | |
}); | |
}); | |
}); | |
</script> | |
<?php | |
endif; | |
} | |
add_filter( 'woocommerce_checkout_posted_data', 'w_add_shipping_warranty_data' ); | |
function w_add_shipping_warranty_data( $data ) { | |
$data['shipping_warranty'] = empty( $_POST['shipping_warranty'] ) ? 0 : 1; | |
return $data; | |
} | |
add_action( 'woocommerce_admin_order_data_after_shipping_address', 'add_shipping_warranty_info_on_order' ); | |
function add_shipping_warranty_info_on_order( $order ) { | |
vprintf( '<p><strong>%1$s</strong> %2$s</p>', array( | |
__( 'Assurance expédition :' ), | |
$order->get_meta( '_shipping_warranty' ) ? 'Souscrite' : 'Non souscrite', | |
) ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment