How to Re-Attach a File to a Post or Page (File Attachment Management)

Snippets by IsItWP

Are you looking for a way to re-attach a file to a post or page? While there’s probably a plugin for this, we have created a quick code snippet that you can use to re-attach a file to a post or page in WordPress.

When a file is uploaded using the “Add Media” button from text editor, that file automatically becomes an attachment of the particular post.

When you delete the post, the media files that are attached to it will be unattached. You can re-attach these media files to a post or page.


All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

add_filter("manage_upload_columns", 'upload_columns');
add_action("manage_media_custom_column", 'media_custom_columns', 0, 2);

function upload_columns($columns) {

	$columns['better_parent'] = "Parent";

	return $columns;

 function media_custom_columns($column_name, $id) {

	$post = get_post($id);

	if($column_name != 'better_parent')

		if ( $post->post_parent > 0 ) {
			if ( get_post($post->post_parent) ) {
				$title =_draft_or_post_title($post->post_parent);
			<strong><a href="<?php echo get_edit_post_link( $post->post_parent ); ?>"><?php echo $title ?></a></strong>, <?php echo get_the_time(__('Y/m/d')); ?>
			<br />
			<a class="hide-if-no-js" onclick="findPosts.open('media[]','<?php echo $post->ID ?>');return false;" href="#the-list"><?php _e('Re-Attach'); ?></a>

		} else {
			<?php _e('(Unattached)'); ?><br />
			<a class="hide-if-no-js" onclick="findPosts.open('media[]','<?php echo $post->ID ?>');return false;" href="#the-list"><?php _e('Attach'); ?></a>


Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 10 best WordPress testimonial plugins to add social proof and how to create a WordPress donation form.

Comments   Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!