WC_REST_Products_V4_Controller::set_product_images
Set product images.
Метод класса: WC_REST_Products_V4_Controller{}
Хуки из метода
Возвращает
WC_Product.
Использование
// protected - в коде основоного (родительского) или дочернего класса $result = $this->set_product_images( $product, $images );
- $product(WC_Product) (обязательный)
- Product instance.
- $images(массив) (обязательный)
- Images data.
Код WC_REST_Products_V4_Controller::set_product_images() WC REST Products V4 Controller::set product images WC 10.3.4
woocommerce/includes/rest-api/Controllers/Version4/Products/class-wc-rest-products-v4-controller.php
protected function set_product_images( $product, $images ) {
$images = is_array( $images ) ? array_filter( $images ) : array();
if ( ! empty( $images ) ) {
$gallery = array();
foreach ( $images as $index => $image ) {
$attachment_id = isset( $image['id'] ) ? absint( $image['id'] ) : 0;
// The request can contain an attachment ID, if it doesn't, it's a new upload.
$is_new_upload = false;
if ( 0 === $attachment_id && 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 suppress the image upload error, false by default.
*/
if ( ! apply_filters( 'woocommerce_rest_suppress_image_upload_error', false, $upload, $product->get_id(), $images ) ) { // phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingSinceComment
throw new WC_REST_Exception( 'woocommerce_product_image_upload_error', $upload->get_error_message(), 400 ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
} else {
continue;
}
}
$attachment_id = wc_rest_set_uploaded_image_as_attachment( $upload, $product->get_id() );
$is_new_upload = true;
}
if ( ! wp_attachment_is_image( $attachment_id ) ) {
/* translators: %s: image ID */
throw new WC_REST_Exception( 'woocommerce_product_invalid_image_id', sprintf( __( '#%s is an invalid image ID.', 'woocommerce' ), $attachment_id ), 400 ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
}
if ( $is_new_upload && $attachment_id > 0 ) {
// Tracking this for rollback purposes.
$this->processed_attachment_ids_for_request[] = $attachment_id;
}
$featured_image = $product->get_image_id();
if ( 0 === $index ) {
$product->set_image_id( $attachment_id );
wc_product_attach_featured_image( $attachment_id, $product, false );
} else {
$gallery[] = $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'],
)
);
}
}
$product->set_gallery_image_ids( $gallery );
} else {
$product->set_image_id( '' );
$product->set_gallery_image_ids( array() );
}
return $product;
}