1

IN WooCommerce, I would like to perform an action if at least one product from a list is bought and if the current order status for that product is completed.

For instance I can only verify if the product is bought:

global $woocommerce;
$user_id = get_current_user_id();
$current_user= wp_get_current_user();
$product_list = array('11', '12', '13', '14', '15','16');
$text= false;
  foreach ($product_list as $value):
    if (wc_customer_bought_product( $customer_email, $user_id, $value) ) {
        $text = true;
     }
  endforeach;
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Beusebiu
  • 1,433
  • 4
  • 23
  • 68
  • And what's your question? Is there anything not working with that code? – Nico Haase May 23 '19 at 09:14
  • This code is working,but is not completed. I need one more condition(if the order is completed ), otherwise the client can do that action and the payment is not done. – Beusebiu May 23 '19 at 10:04

1 Answers1

0

Try the following that will be triggered each time an order gets "completed" status, checking if the current order has specific products from your defined Ids, allowing you to perform an action:

add_action('woocommerce_order_status_completed', 'action_on_order_status_completed', 10, 2 );
function action_on_order_status_completed( $order_id, $order ){
    // Here below define your product id(s)
    $products_ids = array('11', '12', '13', '14', '15','16');
    $found = false; // Initializing
    
    // Loop through order items
    foreach ( $order->get_items() as $item ) {
        if ( array_intersect([$item->get_product_id(), $item->get_variation_id()], $products_ids) ) {
            $found = true;
            break; // Stop the loop
        }
    }
    
    if ( $found ) {
        // HERE do your action
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and work.


Related: How to get WooCommerce order details

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • I tried this code, but the problem is that I have to show a part of a custom page, and I can't access the $found variable from that page. I tried to declare that variable global. But still do not work, and to insert this code in that page,but the result is the same. – Beusebiu May 23 '19 at 10:00
  • I tried to echo/ print_r/ var_dump the action, with this code, and nothing. I double checked product id,and the order is completed. :( – Beusebiu May 23 '19 at 11:23
  • @EusebiuBalan That code doesn't output anything, it just allows to make an action like to update some data, trigger another function… Ask a new question as I have suggested you, including a link to this answer and explaining what do you need to do with much more details and context. Then notify me here. – LoicTheAztec May 23 '19 at 11:32
  • Ok, thanks! I posted another question here: /questions/56274545/for-specific-products-on-woocommerce-orders-with-completed-status-change-inform – Beusebiu May 23 '19 at 11:48