WC_Coupon_Data_Store_CPT::update()publicWC 3.0.0

Updates a coupon in the database.

Method of the class: WC_Coupon_Data_Store_CPT{}

Hooks from the method

Return

null. Nothing (null).

Usage

$WC_Coupon_Data_Store_CPT = new WC_Coupon_Data_Store_CPT();
$WC_Coupon_Data_Store_CPT->update( $coupon );
$coupon(WC_Coupon) (required) (passed by reference — &)
Coupon object.

Changelog

Since 3.0.0 Introduced.

WC_Coupon_Data_Store_CPT::update() code WC 9.4.2

public function update( &$coupon ) {
	$coupon->save_meta_data();
	$changes = $coupon->get_changes();

	if ( array_intersect( array( 'code', 'description', 'date_created', 'date_modified' ), array_keys( $changes ) ) ) {
		$post_data = array(
			'post_title'        => $coupon->get_code( 'edit' ),
			'post_excerpt'      => $coupon->get_description( 'edit' ),
			'post_date'         => gmdate( 'Y-m-d H:i:s', $coupon->get_date_created( 'edit' )->getOffsetTimestamp() ),
			'post_date_gmt'     => gmdate( 'Y-m-d H:i:s', $coupon->get_date_created( 'edit' )->getTimestamp() ),
			'post_modified'     => isset( $changes['date_modified'] ) ? gmdate( 'Y-m-d H:i:s', $coupon->get_date_modified( 'edit' )->getOffsetTimestamp() ) : current_time( 'mysql' ),
			'post_modified_gmt' => isset( $changes['date_modified'] ) ? gmdate( 'Y-m-d H:i:s', $coupon->get_date_modified( 'edit' )->getTimestamp() ) : current_time( 'mysql', 1 ),
		);

		/**
		 * When updating this object, to prevent infinite loops, use $wpdb
		 * to update data, since wp_update_post spawns more calls to the
		 * save_post action.
		 *
		 * This ensures hooks are fired by either WP itself (admin screen save),
		 * or an update purely from CRUD.
		 */
		if ( doing_action( 'save_post' ) ) {
			$GLOBALS['wpdb']->update( $GLOBALS['wpdb']->posts, $post_data, array( 'ID' => $coupon->get_id() ) );
			clean_post_cache( $coupon->get_id() );
		} else {
			wp_update_post( array_merge( array( 'ID' => $coupon->get_id() ), $post_data ) );
		}
		$coupon->read_meta_data( true ); // Refresh internal meta data, in case things were hooked into `save_post` or another WP hook.
	}
	$this->update_post_meta( $coupon );
	$coupon->apply_changes();
	delete_transient( 'rest_api_coupons_type_count' );

	// The `coupon_id_from_code` entry in the object cache must not exist when the coupon is not published, otherwise the coupon will remain available for use.
	if ( 'publish' !== $coupon->get_status() ) {
		wp_cache_delete( WC_Cache_Helper::get_cache_prefix( 'coupons' ) . 'coupon_id_from_code_' . $coupon->get_code(), 'coupons' );
	}

	do_action( 'woocommerce_update_coupon', $coupon->get_id(), $coupon );
}