Skip to content

Instantly share code, notes, and snippets.

@brandonkramer
Last active April 9, 2022 22:49
Show Gist options
  • Save brandonkramer/4939fd26875899c677895f6bca9c6286 to your computer and use it in GitHub Desktop.
Save brandonkramer/4939fd26875899c677895f6bca9c6286 to your computer and use it in GitHub Desktop.
Programmatically change the file path of a single attachment or multiple attachments in WordPress. Can be used in a loop or any other use cases in which you have the attachment_id in hand.
<?php
$attachment_id = $your_way_of_getting_the_id;
$file_path = '2022/02/my-image.jpg';
// Update the path inside the post meta
update_post_meta( $attachment_id, '_wp_attached_file', $attachment_id );
$old_metadata = wp_get_attachment_metadata( $attachment_id );
$old_metadata['file'] = $attachment_id;
// Update the path inside the meta data
wp_update_attachment_metadata( $attachment_id, $old_metadata );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment