WC_REST_Product_Variations_Controller::set_variation_image() protected WC 1.0
Set variation image.
{} It's a method of the class: WC_REST_Product_Variations_Controller{}
Hooks from the method
Return
WC_Product_Variation.
Usage
// protected - for code of main (parent) or child class $result = $this->set_variation_image( $variation, $image );
- $variation(WC_Product_Variation) (required)
- Variation instance.
- $image(array) (required)
- Image data.
Code of WC_REST_Product_Variations_Controller::set_variation_image() WC REST Product Variations Controller::set variation image WC 5.0.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 ) ) {
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;
}