NuclearApe
NuclearApe

Reputation: 603

Delete WooCommerce coupons 30 days after they expire

I have the following function, which deletes WooCommerce coupons on the day they expire.

How do you make it delete them 30 days after their expiry date instead?

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' );

Upvotes: 1

Views: 1058

Answers (2)

Bhautik
Bhautik

Reputation: 11282

You have to compare the current date with the past 30 days date. check the below code.

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' );

Upvotes: 5

rajat.gite
rajat.gite

Reputation: 446

Can you please try this code

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' );

Upvotes: -1

Related Questions