update_attached_file()WP 2.1.0

Updates the path of the attached file (attachment) in the meta-field "_wp_attached_file". The path is updated for the specified attachment ID.

The function does not move the file, but simply updates the meta-field _wp_attached_file, usually after the file has been moved.

This function is used within wp_insert_post() and is usually not used separately.

The meta-field stores not the full path from the server root, but the relative path from the uploads directory.

Instead of this function, you might find the hook-filter update_attached_file useful - it is used in the function before updating the data in the meta-field.

Hooks from the function

Returns

Int|true|false.

  • int — ID of the meta-record if there was no key _wp_attached_file for the attachment.
  • true — on successful update.
  • false — on error. Or if the provided $file matches what is already saved in the database.

Usage

update_attached_file( $attachment_id, $file );
$attachment_id(integer) (required)
ID of the attached file (attachment).
$file(string) (required)
New path to the attachment file that needs to be recorded.

Examples

0

#1 Example of work

Suppose we added a new file and we need to update the path to this file, which is stored in the meta field _wp_attached_file.

update_attached_file( $post_ID, $postarr['file'] );

Changelog

Since 2.1.0 Introduced.

update_attached_file() code WP 6.9.1

function update_attached_file( $attachment_id, $file ) {
	if ( ! get_post( $attachment_id ) ) {
		return false;
	}

	/**
	 * Filters the path to the attached file to update.
	 *
	 * @since 2.1.0
	 *
	 * @param string $file          Path to the attached file to update.
	 * @param int    $attachment_id Attachment ID.
	 */
	$file = apply_filters( 'update_attached_file', $file, $attachment_id );

	$file = _wp_relative_upload_path( $file );
	if ( $file ) {
		return update_post_meta( $attachment_id, '_wp_attached_file', $file );
	} else {
		return delete_post_meta( $attachment_id, '_wp_attached_file' );
	}
}