过期 30 天后删除 WooCommerce 优惠券

Delete WooCommerce coupons 30 days after they expire

我有以下功能,它会在 WooCommerce 优惠券到期日删除它们。

如何让它在 30 天后 到期后删除它们?

function delete_expired_coupons() {
  $args = array(
    'posts_per_page' => -1,
    'post_type'      => 'shop_coupon',
    'post_status'    => 'publish',
    'meta_query'     => array(
      'relation'   => 'AND',
      array(
        'key'     => 'date_expires',
        'value'   => current_time( 'timestamp' ),
        'compare' => '<='
      ),
      array(
        'key'     => 'date_expires',
        'value'   => '',
        'compare' => '!='
      )
    )
  );

  $coupons = get_posts( $args );

  if ( ! empty( $coupons ) ) {
    foreach ( $coupons as $coupon ) {
      wp_trash_post( $coupon->ID );
    }
  }
}
add_action( 'delete_expired_coupons', 'delete_expired_coupons' );

你能试试这个代码吗

function wp_delete_expired_coupons() {
    $args = array(
        'posts_per_page' => -1,
        'post_type'      => 'shop_coupon',
        'post_status'    => 'publish',
        'meta_query'     => array(
            'relation'   => 'AND',
            array(
                'key'     => 'expiry_date',
                'value'   => current_time( 'Y-m-d' ),
                'compare' => '<='
            ),
            array(
                'key'     => 'expiry_date',
                'value'   => '',
                'compare' => '!='
            )
        )
    );

    $coupons = get_posts( $args );

    if ( ! empty( $coupons ) ) {
        <!-- $current_time = current_time( 'timestamp' ); -->

        foreach ( $coupons as $coupon ) {
            wp_trash_post( $coupon->ID );
        }
    }
}
add_action( 'delete_expired_coupons', 'wp_delete_expired_coupons' );

您必须将当前日期与过去 30 天的日期进行比较。检查下面的代码。

function delete_expired_coupons() {

    $args = array(
        'posts_per_page' => -1,
        'post_type'      => 'shop_coupon',
        'post_status'    => 'publish',
        'meta_query'     => array(
            'relation'   => 'AND',
            array(
                'key'     => 'date_expires',
                'value'   => strtotime( '-30 days', current_time( 'timestamp' ) ),
                'compare' => '<='
            ),
            array(
                'key'     => 'date_expires',
                'value'   => '',
                'compare' => '!='
            )
        )
    );

    $coupons = get_posts( $args );

    if ( ! empty( $coupons ) ) {
        foreach ( $coupons as $coupon ) {
            wp_trash_post( $coupon->ID );
        }
    }
    
}
add_action( 'delete_expired_coupons', 'delete_expired_coupons' );