WordPress hooks for saving, trashing, restoring, and deleting custom fields in a custom post type

Various types of fishing hooks.
Hooked on coming up with featured images.

This took me quite a while to figure out, but I finally determined what the proper hooks for managing custom fields in a custom post type in WordPress are.

In my scenario, I have a custom post type that uses the add_meta_box() function to add a few custom fields. As a matter of fact, those are the only fields available… the title, body, etc, have all been removed. Furthermore, I save those custom fields in a new table, because I need to perform additional actions outside of WordPress with that data, and storing them separately will make that a lot easier.

WordPress allows you to perform four actions with any post type, which meant I needed four hooks in order to keep the data in my table in sync with the status of the post. Those actions are: saving, moving something to the trash, restoring it from the trash, and permanently deleting.

It seems that WordPress is a bit inconsistent in the naming convention of those hooks, which is why it took some trial and error, but after spending some time with it, I’ve tested and confirmed the following four hooks to be the ones you need:

Saving

add_action('save_post', 'custom_save_function');

Trashing

add_action('wp_trash_post', 'custom_trash_function');

Restoring

add_action('untrash_post', 'custom_restore_function');

Deleting

add_action('delete_post', 'custom_delete_function');

Hooks that didn’t act the way I expected were: trash_post, wp_untrash_post, trash_custom-post-type, and untrash_custom-post-type. For instance, trash_post only worked with built-in post types, such as pages and posts, but save_post works even with custom post types.

Hopefully this two minute blog post will save someone some time, because those four hooks are pretty much necessary if you’re working with custom fields (unless you disable trash entirely and just permanently delete).

Featured image by Anne Nygård.


Comments (1)

Previously posted in WordPress and transferred to Ghost.

alexidoia
July 15, 2012 at 3:16 pm

Infortunatly, your solutions do not work for all type of action, AJAX update for exemple do not trigger this action, for ex, you select trash from bulk action, it will trigger you wp_trash_post but if the link trash below the title is used then it won’t work.
Idem for the ‘Undo’ link given in the admin message when the items is moved to trash.
And so on. There is a lot of inconsistencies in that matters and they are talking about doing some clean up in the next version. Right now, the only thing I advise it to hide links with CSS and/or Jquery, construct your own bulk actions to trigger your own function and you will be much off the hook (ahah).