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

十年热恋 提交于 2019-12-11 06:14:15

问题


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;

回答1:


Try the following hooked function, that will be triggered each time an order gets "completed" status, checking if the current order has a product from your defined list, 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 your product list
    $products_ids = array('11', '12', '13', '14', '15','16');
    $found = false;

    // Loop through order items
    foreach ( $order->get_items() as $item ) {
        if ( in_array($item->product_id(), $products_ids) ) {
            $found = true;
            break;
        }
    }

    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



来源:https://stackoverflow.com/questions/56271595/for-specific-products-on-woocommerce-orders-with-completed-status-perform-an-ac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!