Last active
April 9, 2022 22:49
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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