如果在 WooCommerce 中没有付款,X 天后自动取消订单

Automatically cancel order after X days if no payment in WooCommerce

我在网上搜索后设法把它放在一起,但它不起作用。我的目标是如果订单在三天后仍未付款,则无论支付网关如何,都自动取消状态为暂停的所有订单。

代码显然不完整,我正在寻求帮助以使其完整。我正在用 -1 minute 测试它,看看是否发生了什么。没有。

function get_unpaid_orders() {
    global $wpdb;

    $unpaid_orders = $wpdb->get_col( $wpdb->prepare( "
        SELECT posts.ID
        FROM {$wpdb->posts} AS posts
        WHERE posts.post_status = 'wc-on-hold'
        AND posts.post_date < %s
    ", date( 'Y-m-d H:i:s', strtotime('-1 minute') ) ) );

    return $unpaid_orders;
}

add_action( 'woocommerce_cancel_unpaid_submitted', 'cancel_unpaid_orders' );
function cancel_unpaid_orders() {
    $unpaid_orders = get_unpaid_orders();

    if ( $unpaid_orders ) {
        foreach ( $unpaid_orders as $unpaid_order ) {
            $order = wc_get_order( $unpaid_order );
            $cancel_order = true;

            foreach  ( $order->get_items() as $item_key => $item_values) {
                $manage_stock = get_post_meta( $item_values, '_manage_stock', true );
                if ( $manage_stock == "yes" ) {
                    $payment_method = $order->get_payment_method();
                    if ( $payment_method == "bacs" ) {
                        $cancel_order = false;
                    }
                }
            }
            if ( $cancel_order == true ) {
                $order -> update_status( 'cancelled', __( 'The order was cancelled due to no payment from customer.', 'woocommerce') );
            }
        }
    }
}

更新 4

注意: 在 WooCommerce 中,there is already a function 挂钩了 woocommerce_cancel_unpaid_orders 操作挂钩,可在 7 天后取消未付款订单。

我没有找到woocommerce_cancel_unpaid_submitted动作挂钩,所以我不知道它是否存在以及是否被触发。

现在您的代码中存在一些错误,您可以更好地使用 wc_get_orders(),它会直接为您提供正确的 WC_Order 对象数组......

这里有一些不同的制作方法(最后一个未经测试):

1) 最后一个解决方案 已经过测试并且有效 当商店经理或管理员用户角色浏览管理员订单列表时 (每天只执行一次):

add_action( 'restrict_manage_posts', 'cancel_unpaid_orders' );
function cancel_unpaid_orders() {
    global $pagenow, $post_type;

    // Enable the process to be executed daily when browsing Admin order list 
    if( 'shop_order' === $post_type && 'edit.php' === $pagenow 
        && get_option( 'unpaid_orders_daily_process' ) < time() ) :

    $days_delay = 5; // <=== SET the delay (number of days to wait before cancelation)

    $one_day    = 24 * 60 * 60;
    $today      = strtotime( date('Y-m-d') );

    // Get unpaid orders (5 days old)
    $unpaid_orders = (array) wc_get_orders( array(
        'limit'        => -1,
        'status'       => 'on-hold',
        'date_created' => '<' . ( $today - ($days_delay * $one_day) ),
    ) );

    if ( sizeof($unpaid_orders) > 0 ) {
        $cancelled_text = __("The order was cancelled due to no payment from customer.", "woocommerce");

        // Loop through orders
        foreach ( $unpaid_orders as $unpaid_order ) {
            $unpaid_order->update_status( 'cancelled', $cancelled_text );
        }
    }
    // Schedule the process to the next day (executed once restriction)
    update_option( 'unpaid_orders_daily_process', $today + $one_day );

    endif;
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。


2) 第三种解决方案 已经过测试并有效:当任何订单更改为 "processing" 或"completed"状态(每天只执行一次):

// Triggered on orders status change to "processing" or "completed"
add_action( 'woocommerce_order_status_changed', 'daily_cancel_unpaid_orders', 10, 4 );
function daily_cancel_unpaid_orders( $order_id, $old_status, $new_status, $order ) {
    // Enable the process to be executed daily
    if( in_array( $new_status, array('processing', 'completed') ) 
        && get_option( 'unpaid_orders_daily_process' ) < time() ) :

    $days_delay = 5; // <=== SET the delay (number of days to wait before cancelation)

    $one_day    = 24 * 60 * 60;
    $today      = strtotime( date('Y-m-d') );

    // Get unpaid orders (5 days old)
    $unpaid_orders = (array) wc_get_orders( array(
        'limit'        => -1,
        'status'       => 'on-hold',
        'date_created' => '<' . ( $today - ($days_delay * $one_day) ),
    ) );

    if ( sizeof($unpaid_orders) > 0 ) {
        $cancelled_text = __("The order was cancelled due to no payment from customer.", "woocommerce");

        // Loop through WC_Order Objects
        foreach ( $unpaid_orders as $order ) {
            $order->update_status( 'cancelled', $cancelled_text );
        }
    }
    // Schedule the process to the next day (executed once restriction)
    update_option( 'unpaid_orders_daily_process', $today + $one_day );

    endif;
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。


3) 所以你可以尝试使用 woocommerce_cancel_unpaid_submitted 动作挂钩:

add_action( 'woocommerce_cancel_unpaid_submitted', 'cancel_unpaid_orders' );
function cancel_unpaid_orders() {
    $days_delay = 5; // <=== SET the delay (number of days to wait before cancelation)

    $one_day    = 24 * 60 * 60;
    $today      = strtotime( date('Y-m-d') );

    // Get unpaid orders (5 days old here)
    $unpaid_orders = (array) wc_get_orders( array(
        'limit'        => -1,
        'status'       => 'on-hold',
        'date_created' => '<' . ( $today - ($days_delay * $one_day) ),
    ) );

    if ( sizeof($unpaid_orders) > 0 ) {
        $cancelled_text = __("The order was cancelled due to no payment from customer.", "woocommerce");

        // Loop through orders
        foreach ( $unpaid_orders as $order ) {
            $order->update_status( 'cancelled', $cancelled_text );
        }
    }
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。

函数代码应该更好用。对于钩子我真的不知道。


4) 您也可以尝试使用 woocommerce_cancel_unpaid_orders 动作挂钩。

只是添加到@LoicTheAztec 的绝妙回答。我将其修改为一个插件,并添加了一个设置页面,您可以在其中 enable/disable 此功能,以及从管理设置中更改延迟天数。这是代码:

<?php
/**
* Plugin Name: Cancel On-Hold Orders After X Days
* Plugin URI: https://smartairfilters.com
* Description: Cancel orders that are in an 'on-hold' status after a certain number of days. Uses wordpress cron to trigger
* Version: 1.0.0
* Author: Paddy Robertson
* Author URI: https://patrickrobertson.uk
* Requires at least: 5.3
* Requires PHP: 7.0
*/

add_action('woocommerce_cancel_unpaid_orders', 'cancel_onhold_orders');
function cancel_onhold_orders() {
  if (!get_option('cancel_onhold_enable')) {
    // only run if feature is enabled
    return;
  }

  $days_delay = get_option('cancel_onhold_days_delay'); // <=== SET the delay (number of days to wait before cancelation)
  echo "days delay   xxxx " . $days_delay;
  $one_day    = 24 * 60 * 60;
  $today      = strtotime( date('Y-m-d') );

  // Get unpaid orders (5 days old here)
  $unpaid_orders = (array) wc_get_orders(array(
    'orderby' => 'date',
    'order' => 'DESC',
    'limit'        => -1,
    'status'       => 'on-hold',
    'date_created' => '<' . ($today - ($days_delay * $one_day)),
  ));

  if ( sizeof($unpaid_orders) > 0 ) {
    $cancelled_text = __("The order was cancelled due to no payment from customer.", "woocommerce");

    // Loop through orders
    foreach ( $unpaid_orders as $order ) {
      $order->update_status( 'cancelled', $cancelled_text );
    }
  }
}

// Settings page
function cancel_onhold_register_settings() {
  register_setting( 'cancel_onhold_group', 'cancel_onhold_days_delay');
  register_setting( 'cancel_onhold_group', 'cancel_onhold_enable');
}

add_action( 'admin_init', 'cancel_onhold_register_settings' );
function cancel_onhold_register_options_page() {
  add_options_page('Cancel On-Hold Orders', 'Cancel On-Hold', 'manage_options', 'cancel_onhold_options_page', 'cancel_onhold_options_page');
}

add_action('admin_menu', 'cancel_onhold_register_options_page');
function cancel_onhold_options_page() {
  ?>
  <div>
    <h2>Cancel On-Hold Orders after X Days</h2>
    <form method="post" action="options.php">
      <?php settings_fields( 'cancel_onhold_group' ); ?>
      <table class="form-table">
        <tr valign="top">
          <th scope="row"><label for="cancel_onhold_enable">Enable/Disable this feature</label></th>
          <td><input type="checkbox" id="cancel_onhold_enable" name="cancel_onhold_enable" value="1" <?php checked(get_option('cancel_onhold_enable')); ?>" /></td>
        </tr>
        <tr valign="top">
          <th scope="row"><label for="cancel_onhold_days_delay">Enter number of days after which on hold orders will be cancelled</label></th>
          <td><input type="number" id="cancel_onhold_days_delay" name="cancel_onhold_days_delay" value="<?php echo get_option('cancel_onhold_days_delay'); ?>" /> days</td>
        </tr>
      </table>
      <?php submit_button(); ?>
    </form>
  </div>
  <?php
}