update_attached_file

Update attachment file path based on attachment ID.

Description

update_attached_file( (int) $attachment_id, (string) $file ); 

Used to update the file path of the attachment, which uses post meta name '_wp_attached_file' to store the path of the attachment.

Parameters (2)

0. $attachment_id (int)
The attachment id.
1. $file (string)
File path for the attachment.

Usage

  1. if ( !function_exists( 'update_attached_file' ) ) { 
  2. require_once ABSPATH . WPINC . '/post.php'; 
  3.  
  4. // The attachment id. 
  5. $attachment_id = -1; 
  6.  
  7. // File path for the attachment. 
  8. $file = ''; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = update_attached_file($attachment_id, $file); 
  12.  

Defined (1)

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

/wp-includes/post.php  
  1. function update_attached_file( $attachment_id, $file ) { 
  2. if ( !get_post( $attachment_id ) ) 
  3. return false; 
  4.  
  5. /** 
  6. * Filters the path to the attached file to update. 
  7. * @since 2.1.0 
  8. * @param string $file Path to the attached file to update. 
  9. * @param int $attachment_id Attachment ID. 
  10. */ 
  11. $file = apply_filters( 'update_attached_file', $file, $attachment_id ); 
  12.  
  13. if ( $file = _wp_relative_upload_path( $file ) ) 
  14. return update_post_meta( $attachment_id, '_wp_attached_file', $file ); 
  15. else 
  16. return delete_post_meta( $attachment_id, '_wp_attached_file' );