Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

php - For specific products on WooCommerce orders with completed status, perform an action

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...