I need to run some custom code any time a specific product is purchased in WooCommerce.
I was able to add an action to the completed purchase hook, but I'm not finding the way to check to see if a certain product ID was purchased or what it's quantity.
The code I'm using is this (In my functions.php):
function add_report_credits() {
$user_id = get_current_user_id();
$key = 'lwpreports';
$single = true;
$user_lwp_credits = get_user_meta($user_id, $key, $single);
$reportsadded = ++$user_lwp_credits;
update_user_meta($user_id, $key, $reportsadded);
}
add_action('woocommerce_payment_complete', 'add_report_credits');
This code adds a value of 1 to the lwpreports user meta after any purchase, but I need to to add a value of 1, for each quantity of product with a specific ID purchased.
Anyone familiar with WooCommerce enough to give some suggestion?
John Cotton answers:
Remove the add_action on your function and use this instead.
function check_report_credits()
global $woocommerce;
$my_id = 1; // set to whatever product id you're interested in
foreach( $woocommerce->cart->cart_contents as $id => $cart_item) {
if( $cart_item['product_id'] == $my_id ) {
// You can also check cart_item['quantity']
add_report_credits();
}
}
}
add_action('woocommerce_payment_complete', 'check_report_credits');
Spencer Tomosvary comments:
WOW! Thank you!
It *almost* works. I don't understand why the foreach loop isn't working, but it just adds one credit, not one for each quantity.. but WOW.
Spencer Tomosvary comments:
Hey John,
Any ideas as to why the foreach loop only runs through once even if there are multiples of the product in the cart?
This code is so close to working, but it still just adds credits only once, even if 2+ of the product are purchased.
Thanks,
Spencer
Spencer Tomosvary comments:
The comment above appeared blank. But the support at WooThemes provided an answer for me.. I needed to nest another loop inside, like this:
function check_report_credits() {
global $woocommerce;
$my_id = 15;
foreach( $woocommerce->cart->cart_contents as $id => $cart_item) {
if ( $cart_item['product_id'] == $my_id ) {
for ($i=1; $i<=$cart_item['quantity']; $i++) {
add_report_credits();
}
}
}
}
add_action('woocommerce_payment_complete', 'check_report_credits');
Francisco Javier Carazo Gil answers:
Hi Spencert,
WooCommerce use custom post types to define products, so you can directly get product id in the same way you get a post ID.