wc_rest_set_uploaded_image_as_attachment

Set uploaded image as attachment.

Description

(int) wc_rest_set_uploaded_image_as_attachment( (array) $upload, (int) $id = 0 ); 

Returns (int)

Attachment ID

Parameters (2)

0. $upload (array)
Upload information from wp_upload_bits.
1. $id — Optional. (int)
Post ID. Default to 0.

Usage

  1. if ( !function_exists( 'wc_rest_set_uploaded_image_as_attachment' ) ) { 
  2. require_once ABSPATH . PLUGINDIR . 'woocommerce/includes/wc-rest-functions.php'; 
  3.  
  4. // Upload information from wp_upload_bits. 
  5. $upload = array(); 
  6.  
  7. // Post ID. Default to 0. 
  8. $id = -1; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = wc_rest_set_uploaded_image_as_attachment($upload, $id); 
  12.  

Defined (1)

The function is defined in the following location(s).

/includes/wc-rest-functions.php  
  1. function wc_rest_set_uploaded_image_as_attachment( $upload, $id = 0 ) { 
  2. $info = wp_check_filetype( $upload['file'] ); 
  3. $title = ''; 
  4. $content = ''; 
  5.  
  6. if ( ! function_exists( 'wp_generate_attachment_metadata' ) ) { 
  7. include_once( ABSPATH . 'wp-admin/includes/image.php' ); 
  8.  
  9. if ( $image_meta = wp_read_image_metadata( $upload['file'] ) ) { 
  10. if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) { 
  11. $title = wc_clean( $image_meta['title'] ); 
  12. if ( trim( $image_meta['caption'] ) ) { 
  13. $content = wc_clean( $image_meta['caption'] ); 
  14.  
  15. $attachment = array( 
  16. 'post_mime_type' => $info['type'],  
  17. 'guid' => $upload['url'],  
  18. 'post_parent' => $id,  
  19. 'post_title' => $title,  
  20. 'post_content' => $content,  
  21. ); 
  22.  
  23. $attachment_id = wp_insert_attachment( $attachment, $upload['file'], $id ); 
  24. if ( ! is_wp_error( $attachment_id ) ) { 
  25. wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $upload['file'] ) ); 
  26.  
  27. return $attachment_id;