Publish Action Hook for Custom Post Types

September 30th, 2010

Most of the time, when a developer wants to make something happen every time a post is published, such as send out an email notification, they use

1
add_action('publish_post', 'the_function_to_perform');

This works great, but with one, major problem: it doesn’t work for custom post types.

While working on an update to my WordPress Announcements plugin, I ran into a problem because publish_post did not work for my custom post type. After several hours of digging, I came across this: {$new_status}_{$post->post_type}, and it did exactly what I wanted it to do: perform an action every time a certain custom post type is published.

It works like this:

1
add_action('publish_custom_post_type_name', 'function_to_perform');

where “custom_post_type_name” is the name of your custom post type. So if you have a post type of “music”, your hook would like this:

1
add_action('publish_music', 'function_to_perform');

Perfect!

This allowed me to do exactly what I needed to do for my plugin update. So what is this update? Well, I’m not going to come straight out and tell you, except to say that it has to do with really cool announcement notifications. You should check out the WordPress Announcements plugin, and follow me on Twitter to stay informed about the update coming any day now.

2 Responses to “Publish Action Hook for Custom Post Types”

  1. October 23, 2010 at 12:29 am

    Awesome, It took me about 5 minutes to google and find the answer as to why my publish_post hook stopped working for my custom posts. Your hours of digging, saved me hours of digging!

    Thank you

  2. October 24, 2010 at 6:13 pm

    Glad to help :)

Leave a Reply