首页 > 解决方案 > 过期 30 天后删除 WooCommerce 优惠券

问题描述

我有以下功能,它会在 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' );

标签: phpwordpressdatetimewoocommercecoupon

解决方案


您必须将当前日期与过去 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' );

推荐阅读