Plugin: Prevent automatically attaching unattached attachments when inserting into post - Cobbled Code

In an effort to keep things simple for the user (and to separately store the post content and its images), we decided to automatically create an image gallery from all images attached to a post. To add an image to a post’s image gallery, the user just needed to upload an image to that the post, without inserting it into the post content. Voilá, great for product pages and such.

As things go it turns out that this makes it impossible super inconvenient to also add images, say a sponsor logo, to the post content if you did not intend for that image to end up in the post’s gallery as well.

Curiously, when you insert an item into the post content via the media modal’s ‘Media Library’ tab: even when you did not upload that image via the current post edit screen, WordPress will mark that attachment as attached to that specific post if it was not already attached to another post. Now what?

Filters to the rescue

add_filter( 'wp_insert_post_parent', 'prefix_filter_insert_post_parent', 10, 2 );

function prefix_filter_insert_post_parent( $post_parent, $post_ID ) {

	// The 'send-attachment-to-editor' action is set when inserting attachments into the editor.
	if ( ! isset( $_REQUEST['action'] ) || 'send-attachment-to-editor' !== $_REQUEST['action'] ) {
		return $post_parent;
	}

	$post_before = get_post( $post_ID );

	// If the attachment already has a parent, return its ID.
	if ( 0 !== $post_before->post_parent ) {
		return $post_parent;
	}

	// Else, sadly, but convenient for us, the attachment needs to stay an orphan...
	return 0;
}

In the unlikely case you run into the same problem: the XQR-Z100A WordPress plugin takes care of that now.

Thanks for your help J.D.!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.