WC_Coupon_Data_Store_CPT::update_usage_count_meta()privateWC 3.0.0

Increase or decrease the usage count for a coupon by 1.

Method of the class: WC_Coupon_Data_Store_CPT{}

No Hooks.

Return

Int. New usage count

Usage

// private - for code of main (parent) class only
$result = $this->update_usage_count_meta( $coupon, $operation );
$coupon(WC_Coupon) (required) (passed by reference — &)
Coupon object.
$operation(string)
'increase' or 'decrease'.
Default: 'increase'

Changelog

Since 3.0.0 Introduced.

WC_Coupon_Data_Store_CPT::update_usage_count_meta() code WC 9.4.2

private function update_usage_count_meta( &$coupon, $operation = 'increase' ) {
	global $wpdb;
	$id       = $coupon->get_id();
	$operator = ( 'increase' === $operation ) ? '+' : '-';

	add_post_meta( $id, 'usage_count', $coupon->get_usage_count( 'edit' ), true );
	$wpdb->query(
		$wpdb->prepare(
			// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			"UPDATE $wpdb->postmeta SET meta_value = meta_value {$operator} 1 WHERE meta_key = 'usage_count' AND post_id = %d;",
			$id
		)
	);

	$this->refresh_coupon_data( $coupon );

	// Get the latest value direct from the DB, instead of possibly the WP meta cache.
	return (int) $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = 'usage_count' AND post_id = %d;", $id ) );
}