WC_REST_Product_Variations_Controller::set_variation_image()protectedWC 1.0

Set variation image.

Метод класса: WC_REST_Product_Variations_Controller{}

Возвращает

WC_Product_Variation.

Использование

// protected - в коде основоного (родительского) или дочернего класса
$result = $this->set_variation_image( $variation, $image );
$variation(WC_Product_Variation) (обязательный)
Variation instance.
$image(массив) (обязательный)
Image data.

Код WC_REST_Product_Variations_Controller::set_variation_image() WC 8.7.0

protected function set_variation_image( $variation, $image ) {
	$attachment_id = isset( $image['id'] ) ? absint( $image['id'] ) : 0;

	if ( 0 === $attachment_id ) {
		if ( isset( $image['src'] ) ) {
			$upload = wc_rest_upload_image_from_url( esc_url_raw( $image['src'] ) );

			if ( is_wp_error( $upload ) ) {
				/**
				 * Filter to check if it should supress the image upload error, false by default.
				 *
				 * @since 4.5.0
				 * @param bool false   If it should suppress.
				 * @param array         $upload Uploaded image array.
				 * @param int id   Variation id.
				 * @param array    Array of image to set.
				 */
				if ( ! apply_filters( 'woocommerce_rest_suppress_image_upload_error', false, $upload, $variation->get_id(), array( $image ) ) ) {
					throw new WC_REST_Exception( 'woocommerce_variation_image_upload_error', $upload->get_error_message(), 400 );
				}
			}

			$attachment_id = wc_rest_set_uploaded_image_as_attachment( $upload, $variation->get_id() );
		} else {
			$variation->set_image_id( '' );
			return $variation;
		}
	}

	if ( ! wp_attachment_is_image( $attachment_id ) ) {
		/* translators: %s: attachment ID */
		throw new WC_REST_Exception( 'woocommerce_variation_invalid_image_id', sprintf( __( '#%s is an invalid image ID.', 'woocommerce' ), $attachment_id ), 400 );
	}

	$variation->set_image_id( $attachment_id );

	// Set the image alt if present.
	if ( ! empty( $image['alt'] ) ) {
		update_post_meta( $attachment_id, '_wp_attachment_image_alt', wc_clean( $image['alt'] ) );
	}

	// Set the image name if present.
	if ( ! empty( $image['name'] ) ) {
		wp_update_post(
			array(
				'ID'         => $attachment_id,
				'post_title' => $image['name'],
			)
		);
	}

	return $variation;
}