I’m trying to update a custom field after a post thumbnail (Featured Image) is either added or removed from a post. The aim of this is to keep track of whether a featured image has been added or removed in order to do a synchronised export of only the updated ‘dirty’ posts for use in an external service.
I’ve looked throughout the codex for a hook that would be triggered after a post_thumbnail is set but I haven’t been able to find anything. The solution I’d hoped would work was to use the slimly documented ‘updated_post_meta’ action (not to be confused with ‘update_post_meta’!), using the following code:
add_action('updated_post_meta', 'check_dirty_fields_updated_post_meta', 10, 4);
function check_dirty_fields_updated_post_meta($meta_id, $post_id, $meta_key, $meta_value) {
if ('_thumbnail_id' == $meta_key) {
update_post_meta($post_id, 'thumbnails_dirty', 1);
}
if ('schedule' == $meta_key) {
update_post_meta($post_id, 'schedule_dirty', 1);
}
}
So, ‘updated_post_meta’ should be triggered whenever post_meta is updated, but unfortunately ‘_thumbnail_id’ never gets triggered so the ‘thumbnails_dirty’ custom field that I subsequently want to set doesn’t get updated.
You’ll see from that code that I’m also checking to see if a meta_key of ‘schedule’ is ever updated and then marking another custom field called ‘schedule_dirty’ (the ‘schedule’ post_meta value is a custom field that gets set within the standard post UI) In the case of this more standard custom field the ‘updated_post_meta’ action does see it when it’s updated and set the ‘schedule_dirty’ as intended.
The problem I have is that I can’t see why the ‘_thumbnail_id’ post_meta isn’t triggering the ‘updated_post_meta’ action.
Compounding the problem further I just can’t find any clear documentation on when the post thumbnail is set and subsequently updating it’s related ‘_thumbnail_id’ post_meta field. I note that when setting the Featured Image on a post that this is set straight away and therefore does not seem to be dependent on the ‘save_post’ action, so whilst I have looked through various aspects related to saving posts I think the answer lies elsewhere.
A few other bits of info that might be relevant to know:
-
The posts in question here are a custom post type
-
I’m also using the Multiple Post Thumbnails plugin and
subsequently want to check for the updated state of these additional
post thumbnails too.