Created
January 29, 2022 00:20
-
-
Save willybahuaud/a56f6640c2b6c23f6f14bc0e139f072d to your computer and use it in GitHub Desktop.
Ajouter un produit gratuit dans chaque commande Woocommerce (après paiement)
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_filter( 'woocommerce_get_settings_products', 'woo_settings_free_products' ); | |
function woo_settings_free_products( $settings ) { | |
$settings[] = array( | |
'name' => __( 'Produits gratuits', 'woocommerce' ), | |
'type' => 'title', | |
'id' => 'free_products' | |
); | |
$settings[] = array( | |
'name' => __( 'Produits gratuits à ajouter à chaque commande', 'woocommerce' ), | |
'type' => 'text', | |
'id' => 'free_products', | |
'desc' => 'Saisissez les IDs des produits, séparés par une virgule', | |
'default' => '', | |
); | |
$settings[] = array( | |
'type' => 'sectionend', | |
'id' => 'free_products' | |
); | |
return $settings; | |
} | |
add_action( 'woocommerce_payment_complete','maybe_add_free_product_after_order_complete', 100 ); | |
function maybe_add_free_product_after_order_complete( $order_id ) { | |
$free_products = get_option( 'free_products' ); | |
if ( empty( $free_products ) ) { | |
return; | |
} | |
$free_products = explode( ',', $free_products ); | |
$free_products = array_filter( $free_products ); | |
$free_products = array_map( 'trim', $free_products ); | |
$free_products = array_map( 'intval', $free_products ); | |
if ( empty( $free_products ) ) { | |
return; | |
} | |
$order = wc_get_order( $order_id ); | |
if ( is_wp_error( $order ) ) { | |
return; | |
} | |
foreach ( $free_products as $product ) { | |
$product_item = wc_get_product( $product ); | |
$order->add_product( $product_item, 1, array( 'total' => 0, 'subtotal' => 0 ) ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment