Last active
April 24, 2018 21:35
-
-
Save scgoeswild/863e9502d9155774bd1e9107e417a152 to your computer and use it in GitHub Desktop.
Woocommerce every 2 product the third (randomly) is free
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( 'wp', 'add_free_product_to_cart' ); | |
function add_free_product_to_cart( ) { | |
if (!is_admin()) { | |
$count = 1; | |
$count_free = 0; | |
$query = new WC_Product_Query(); | |
$products = $query->get_products(); | |
foreach ( WC()->cart->get_cart() as $cart_item_key => $item ) { | |
if(isset($item['variation']['Type'])){ | |
if($item['variation']['Type'] =='Free Item') { | |
WC()->cart->remove_cart_item($item['key']); | |
} | |
} | |
} | |
foreach ( WC()->cart->get_cart() as $cart_item_key => $item ) { | |
for ($i=0; $i < $item['quantity']; $i++) { | |
if( $count % 3 == 0) { | |
$randid = $products[rand(0, count($products)-1)]->get_id(); | |
WC()->cart->add_to_cart( $randid, 1, 0, [ 'Type' => 'Free Item' ] ); | |
} | |
$count++; | |
} | |
} | |
foreach ( WC()->cart->get_cart() as $cart_item_key => $item ) { | |
if(isset($item['variation']['Type'])){ | |
if($item['variation']['Type'] =='Free Item') { | |
$item['data']->set_price(0); | |
} | |
} | |
} | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment