update_attached_file() WordPress Function

The update_attached_file() function is used to update the attached file for a given post. This function can be used to move an attached file to a new location, or to update the attached file's name.

update_attached_file( int $attachment_id, string $file ) #

Update attachment file path based on attachment ID.


Description

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


Top ↑

Parameters

$attachment_id

(int)(Required)Attachment ID.

$file

(string)(Required)File path for the attachment.


Top ↑

Return

(bool) True on success, false on failure.


Top ↑

Source

File: wp-includes/post.php

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' );
	}
}


Top ↑

Changelog

Changelog
VersionDescription
2.1.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More