Skip to content

Instantly share code, notes, and snippets.

@willybahuaud
Last active February 9, 2022 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willybahuaud/96eaf22e340cead70239626ddfebea7c to your computer and use it in GitHub Desktop.
Save willybahuaud/96eaf22e340cead70239626ddfebea7c to your computer and use it in GitHub Desktop.
Faire des coupons Woocommerce auto-applicables
<?php
add_action( 'woocommerce_coupon_options', 'w_coupons_options', 10, 2 );
function w_coupons_options( $id, $coupon ) {
woocommerce_wp_checkbox(
array(
'id' => 'auto_applied',
'label' => __( 'Activé automatiquement', 'woocommerce' ),
'description' => 'Cocher cette case pour ajouter automatiquement le coupon s’il est disponible pour le panier',
'value' => wc_bool_to_string( get_post_meta( $id, 'auto_applied', true ) ),
)
);
}
add_action( 'woocommerce_coupon_options_save', 'save_auto_apply_coupond_meta');
function save_auto_apply_coupond_meta( $post_id ) {
$auto_applied = ! empty( $_POST['auto_applied'] ) ? 'yes' : 'no';
update_post_meta( $post_id, 'auto_applied', $auto_applied );
}
add_action( 'template_redirect', 'need_auto_apply_coupons' );
function need_auto_apply_coupons() {
if ( is_cart() || is_checkout() ) {
auto_apply_coupons();
}
}
function get_auto_appliable_coupons() {
$coupons = get_posts( array(
'post_type' => 'shop_coupon',
'status' => 'publish',
'fields' => 'ids',
'meta_query' => array(
array(
array(
'key' => 'auto_applied',
'value' => 'yes',
),
),
array(
'relation' => 'OR',
array(
'key' => 'date_expires',
'value' => NULL,
),
array(
'key' => 'date_expires',
'value' => strtotime( 'now' ),
'compare' => '>',
),
),
)
) );
}
function auto_apply_coupons() {
$coupons = get_auto_appliable_coupons();
$cart = WC()->cart;
foreach ( $coupons as $c ) {
$coupon = new WC_Coupon( $c );
$code = $coupon->get_code();
if ( ! $cart->has_discount( $code ) ) {
$WC_Discounts = new WC_Discounts( WC()->cart );
if ( ! is_wp_error( $WC_Discounts->is_coupon_valid( $coupon ) ) ) {
WC()->cart->apply_coupon( $code );
}
}
}
return false;
}
add_aciton( 'woocommerce_before_save_order_items', 'w_apply_coupon_on_save_order', 10, 2 );
function w_apply_coupon_on_save_order( $order_id, $items ) {
$order = wc_get_order( $order_id );
$order_coupons = $order->get_coupon_codes();
$coupons = get_auto_appliable_coupons();
foreach ( $coupons as $c ) {
$coupon = new WC_Coupon( $c );
$code = $coupon->get_code();
if ( ! in_array( $code, $order_coupons ) ) {
$WC_Discounts = new WC_Discounts( $order );
if ( ! is_wp_error( $WC_Discounts->is_coupon_valid( $coupon ) ) ) {
$order->apply_coupon( $code );
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment