[30691] Fix: Reset attachment post_parent when featured image is removed #8925
+34
−2
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
trac: https://core.trac.wordpress.org/ticket/30691
Problem
When a featured image is removed from a post, WordPress only deletes the _thumbnail_id meta field but doesn't reset the attachment's post_parent field back to 0. This creates orphaned relationships where attachments still reference deleted parent posts, causing incorrect results when using functions like get_children() and get_posts().
For Example:
Set image ID 123 as the featured image for post ID 456
Remove the featured image from post 456
Image 123 still has post_parent = 456 in wp_posts table
get_children(456) incorrectly returns image 123 as a child
Root Cause
The delete_post_thumbnail() function in wp-includes/post.php only removes the post meta. Additionally, set_post_thumbnail() doesn't properly establish the post_parent relationship when setting a featured image.
Solution
This PR enhances both functions to properly manage the post_parent relationship:
delete_post_thumbnail():
Retrieves the current thumbnail ID before deletion
Removes the _thumbnail_id meta field
Resets the attachment's post_parent to 0 if it was set to the current post
set_post_thumbnail():
Sets the _thumbnail_id meta field
Updates the attachment's post_parent to establish a proper relationship