Exclude specific products on auto-complete orders process in Woocommerce

笑着哭i 提交于 2019-12-13 18:19:25

问题


I’m currently using the code from this answer thread to auto-complete orders so that new WooCommerce bookings are added to the calendar, (They only get added once marked as complete).

This works great for bookings, however, I’d like to exclude some other products from auto-completing.

Do you know if this is possible?


回答1:


Iterating through order items is a heavier process, than making a much more lighter SQL query.

Here is a custom conditional function that will check for products Ids in a Woocommerce Order (returning true or false):

function order_has_products( $order_id, $product_ids ){
    $product_ids = implode( "','", $product_ids );
    global $wpdb;
    $result = $wpdb->get_var( "
        SELECT COUNT(woim.meta_value) FROM {$wpdb->prefix}woocommerce_order_itemmeta as woim
        INNER JOIN {$wpdb->prefix}woocommerce_order_items as woi ON woi.order_item_id = woim.order_item_id
        WHERE woi.order_id = $order_id AND woim.meta_key IN ('_product_id','_variation_id')
        AND woim.meta_value IN ('$product_ids')
    " );
    return $result > 0 ? true : false;
}

Then you will use it in this way:

add_action('woocommerce_thankyou', 'wc_auto_complete_order', 20, 1);
function wc_auto_complete_order($order_id){
    if (!$order_id)  return;

    // HERE define your Product Ids to exclude in the array 
    $product_ids = array( 37, 53 );

    // Get an instance of the WC_Product object
    $order = wc_get_order($order_id);

    $found  = order_has_products( $order_id, $product_ids );

    if ( in_array( $order->get_payment_method(), array('cod', 'cheque', '') ) || $found ) {
        return;
    }
    else {
        $order->update_status('completed');
    }

}

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


WooCommerce: Auto complete paid Orders (depending on Payment methods)



来源:https://stackoverflow.com/questions/51816785/exclude-specific-products-on-auto-complete-orders-process-in-woocommerce

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