Make WordPress Core

Opened 4 weeks ago

Last modified 4 weeks ago

#49614 new defect (bug)

Add an action for wp_media_attach_action events

Reported by: jonoaldersonwp Owned by:
Milestone: 5.5 Priority: normal
Severity: normal Version:
Component: Media Keywords: good-first-bug has-patch
Focuses: administration Cc:

Description (last modified by jonoaldersonwp)

When a user attaches or detaches media to/from a post, wp_media_attach_action() is called.

See https://github.com/WordPress/WordPress/blob/master/wp-admin/includes/media.php#L3694

This function sets or removes a post_parent value on an attachment post by updating $wpdb->posts.

At the moment, there's no way for plugins or integrations to take action based on these events; making it incredibly difficult to alter or add to the behaviour or outcomes of these processes.

To address this, we should add an action hook following the successful execution of the query (i.e., if $results returns true), using either of the following approaches:

  • do_action('wp_media_attach_action', $attach, $attachment_id, $parent_id) (where $attach is true for 'attach' actions, and false for 'detach' actions); OR
  • Conditionally either do_action('wp_media_attach_action_attach', $attachment_id, $parent_id) or do_action('wp_media_attach_action_detach', $attachment_id, $parent_id).

This will allow plugins and integrations to take arbitrary action based on attaching/detaching media, with the option to consider the type of action, the parent, and the attachment itself.

Note that I considered that clean_attachment_cache() is hookable (and executed in the wp_media_attach_action() function), but only passes the post_id; lacking the critical context of the parent, and the attachment/detachment status. This also appears to fire before any validation that the query was successful, which strikes me as strange.

Attachments (2)

49614.patch (801 bytes) - added by rebasaurus 4 weeks ago.
I've moved the clean_attachment_cache() after the $result check as well.
49614.2.diff (971 bytes) - added by donmhico 16 hours ago.
Add param docs.

Download all attachments as: .zip

Change History (7)

#1 @jonoaldersonwp
4 weeks ago

  • Description modified (diff)

#2 @johnbillion
4 weeks ago

  • Component changed from General to Media
  • Keywords needs-patch good-first-bug added

This ticket was mentioned in Slack in #core-media by pbiron. View the logs.

4 weeks ago

#4 @antpb
4 weeks ago

  • Milestone changed from Awaiting Review to 5.5

This would be a really great one to have added for 5.5. Going to move it into the milestone so we can keep track of it. :)

4 weeks ago

I've moved the clean_attachment_cache() after the $result check as well.

#5 @rebasaurus
4 weeks ago

  • Keywords has-patch added; needs-patch removed

16 hours ago

Add param docs.

Note: See TracTickets for help on using tickets.