WC_API_Products::set_product_image_as_attachment() protected WC 2.2
Sets product image as attachment and returns the attachment ID.
{} It's a method of the class: WC_API_Products{}
No Hooks.
Return
Int.
Usage
// protected - for code of main (parent) or child class $result = $this->set_product_image_as_attachment( $upload, $id );
- $upload(array) (required)
- -
- $id(int) (required)
- -
Changelog
Since 2.2 | Introduced. |
Code of WC_API_Products::set_product_image_as_attachment() WC API Products::set product image as attachment WC 5.0.0
protected function set_product_image_as_attachment( $upload, $id ) {
$info = wp_check_filetype( $upload['file'] );
$title = '';
$content = '';
if ( $image_meta = @wp_read_image_metadata( $upload['file'] ) ) {
if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
$title = wc_clean( $image_meta['title'] );
}
if ( trim( $image_meta['caption'] ) ) {
$content = wc_clean( $image_meta['caption'] );
}
}
$attachment = array(
'post_mime_type' => $info['type'],
'guid' => $upload['url'],
'post_parent' => $id,
'post_title' => $title,
'post_content' => $content,
);
$attachment_id = wp_insert_attachment( $attachment, $upload['file'], $id );
if ( ! is_wp_error( $attachment_id ) ) {
wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $upload['file'] ) );
}
return $attachment_id;
}