Home > Mobile >  Store when a coupon last time was used in WooCommerce
Store when a coupon last time was used in WooCommerce

Time:04-30

I need to record the date of the last time each coupon was used in WooCommerce.

I have seen that the post_meta table saves a used_by record with the emails of the clients who used it, but there is no date record.

Looking for filters I think this one can help me to also record the date:

woocommerce_increase_coupon_usage_count

Can someone guide me on how to add that record?

CodePudding user response:

The woocommerce_increase_coupon_usage_count action hook can indeed be used. Then it's just a matter of creating metadata with the desired value

So you get:

function action_woocommerce_increase_coupon_usage_count( $coupon, $new_count, $used_by ) {
    // Parse about any English textual datetime description into a Unix timestamp
    $now = strtotime( 'now' );

    $coupon->update_meta_data( '_coupon_last_time_used', $now );
    $coupon->save();
}
add_action( 'woocommerce_increase_coupon_usage_count', 'action_woocommerce_increase_coupon_usage_count', 10, 3 );

To retrieve the data:

  1. When you have access to $coupon object
// Get meta
$last_time_used = $coupon->get_meta( '_coupon_last_time_used' );
  1. Via get_post_meta()
$coupon_id = 1001;
$last_time_used = get_post_meta( $coupon_id, '_coupon_last_time_used', true );

CodePudding user response:

Another solution is here. You can try this solution.

add_action( 'woocommerce_new_order', 'create_invoice_for_wc_order',  1, 2  );
function create_invoice_for_wc_order( $order_id, $order ) {
    foreach( $order->get_coupon_codes() as $coupon_code ){
        $coupon_post_obj = get_page_by_title($coupon_code, OBJECT, 'shop_coupon');
        $coupon_id       = $coupon_post_obj->ID;
        $date = date('Y-m-d H:i:s');
        update_post_meta($coupon_id, '_coupon_last_used', $date );
    }   
}
  • Related