0

I'm looking to add some client-side (JavaScript) events to the post edit screen of wp-admin (post.php?action=edit). I wish to fire events when the user selects a new featured image and a different event when they remove the featured image.

So far I've been able to find this wordpress.se answer, which has allowed me to hook into the "on featured image set" event, however I'm at a loss as to how to hook into the "on featued image removed" event, as it pertains to the client.

I've dug into wp.media.featuredImage.frame().states._events a little bit using Chrome's WebInspector, but there doesn't seem to be an event registered that quite matches what I'm looking for...

wp.media.featuredImage.frame().states._events

The only one that jumps out at me as a potential candidate is the content:render:edit-image event, but it doesn't fire during either of the events I'm trying to listen for!

Does anyone know of a way to do this?

2

So I was able to achieve what I wanted, albeit in a bit of a roundabout way. I'll share my solution here in case anyone stumbles across this post looking to do something similar.

Rather than adding an event listener to some unset event (that doesn't exist) on the object returned by wp.media.featuredImage.frame(), I instead added my own onclick event listener to the #remove-post-thumbnail link element. This feels a little hacky to me, since its not directly tied to the unset of a featured image, however since there's no prompt to verify removal, the user interaction is fairly seemless.

There is a caveat with this solution, however - there is already an onclick event bound to that link, so you need to avoid overriding that, or else you won't be able to actually remove the featured image. Originally I tried capturing that default onclick event and then calling it from within my own event that overrides it, like so:

DO NOT DO THIS

var ogCallback = document.getElementById('remove-post-thumbnail').onclick;
document.getElementById('remove-post-thumbnail').onclick = function(e) {
    // My code - do some things
    // ...
    ogCallback(e);
}

But this made WordPress a little buggy when removing the featured image, likely due to some JavaScript scoping that I wasn't taking into account. Because I'm also leveraging jQuery (this is a judgment-free zone, right?) I was able to use jQuery's event binding system instead, and avoid overriding the default behaviour, allowing my custom code to run in tandem with WordPress' featured image removal logic:

DO THIS

$(document).on('click', '#remove-post-thumbnail', function(){
    // Do stuff. Don't let your dreams be dreams
});
  • Excellent explanation, and good to see you coming back to share your solution. – montrealist Dec 29 '15 at 16:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.