cf_custom_fields_attach_file

Handle file fields.

Description

(int) cf_custom_fields_attach_file( (string) $file, (string) $entry_id ); 

Returns (int)

Attachment ID.

Parameters (2)

0. $file (string)
File path.
1. $entry_id (string)
The entry id.

Usage

  1. if ( !function_exists( 'cf_custom_fields_attach_file' ) ) { 
  2. require_once ABSPATH . PLUGINDIR . 'caldera-custom-fields/includes/to-post-type.php'; 
  3.  
  4. // File path. 
  5. $file = ''; 
  6.  
  7. // The entry id. 
  8. $entry_id = ''; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = cf_custom_fields_attach_file($file, $entry_id); 
  12.  

Defined (1)

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

/includes/to-post-type.php  
  1. function cf_custom_fields_attach_file( $file, $entry_id ) { 
  2.  
  3. // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it. 
  4. require_once( ABSPATH . 'wp-admin/includes/image.php' ); 
  5.  
  6. // Check the type of file. We'll use this as the 'post_mime_type'. 
  7. $filetype = wp_check_filetype( basename( $file ), null ); 
  8.  
  9. // Get the path to the upload directory. 
  10. $wp_upload_dir = wp_upload_dir(); 
  11.  
  12. $filename = $wp_upload_dir['path'] . '/' . basename( $file ); 
  13. $attachment = array( 
  14. 'guid' => $wp_upload_dir['url'] . '/' . basename( $file ),  
  15. 'post_mime_type' => $filetype['type'],  
  16. 'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $file ) ),  
  17. 'post_content' => '',  
  18. 'post_status' => 'inherit' 
  19. ); 
  20.  
  21. // Insert the attachment. 
  22. $attach_id = wp_insert_attachment( $attachment, $filename, $entry_id ); 
  23.  
  24. // Generate the metadata for the attachment, and update the database record. 
  25. $attach_data = wp_generate_attachment_metadata( $attach_id, $filename ); 
  26. wp_update_attachment_metadata( $attach_id, $attach_data ); 
  27.  
  28. return $attach_id; 
  29.