WC_Coupon_Data_Store_CPT::decrease_usage_count()publicWC 3.0.0

Decrease usage count for current coupon.

Method of the class: WC_Coupon_Data_Store_CPT{}

Return

Int. New usage count.

Usage

$WC_Coupon_Data_Store_CPT = new WC_Coupon_Data_Store_CPT();
$WC_Coupon_Data_Store_CPT->decrease_usage_count( $coupon, $used_by );
$coupon(WC_Coupon) (required) (passed by reference — &)
Coupon object.
$used_by(string)
Either user ID or billing email.
Default: ''

Changelog

Since 3.0.0 Introduced.

WC_Coupon_Data_Store_CPT::decrease_usage_count() code WC 9.4.2

public function decrease_usage_count( &$coupon, $used_by = '' ) {
	global $wpdb;
	$new_count = $this->update_usage_count_meta( $coupon, 'decrease' );
	if ( $used_by ) {
		/**
		 * We're doing this the long way because `delete_post_meta( $id, $key, $value )` deletes.
		 * all instances where the key and value match, and we only want to delete one.
		 */
		$meta_id = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = '_used_by' AND meta_value = %s AND post_id = %d LIMIT 1;",
				$used_by,
				$coupon->get_id()
			)
		);
		if ( $meta_id ) {
			delete_metadata_by_mid( 'post', $meta_id );
			$coupon->set_used_by( (array) get_post_meta( $coupon->get_id(), '_used_by' ) );
			$this->refresh_coupon_data( $coupon );
		}
	}

	do_action( 'woocommerce_decrease_coupon_usage_count', $coupon, $new_count, $used_by );

	return $new_count;
}