publish_post
doesn't work for custom post types, the correct hook (action hook) is publish_{$custom_post_type}
. You should use add_action()
as this is an action hook.
I also tend to make use of the transition_post_status
hook which is a much more universal hook as it fires everytime a post's status is changed regardless. You can use $old_status
and $new_status
to check the previous and new status of a post then do something.
For a new post, you can something like this: (Requires PHP 5.3+)
add_action( 'transition_post_status', function ( $new_status, $old_status, $post )
{
if( 'publish' == $new_status && 'publish' != $old_status && $post->post_type == 'my_post_type' ) {
//DO SOMETHING IF NEW POST IN POST TYPE IS PUBLISHED
}
}, 10, 3 );
EDIT
For post edits/updates, using transition_post_status
, you can do
add_action( 'transition_post_status', function ( $new_status, $old_status, $post )
{
if( 'publish' == $new_status && 'publish' == $old_status && $post->post_type == 'my_post_type' ) {
//DO SOMETHING IF A POST IN POST TYPE IS EDITED
}
}, 10, 3 );
For further reading regarding post status transition, you can check out the codex
EDIT 2
Custom fields, buildbuilt in and from the advanced custom fields plugin uses the save_post
hook, which runs after post transition, so trying to add custom fields won't work on here
For custom post types, a new hook was introduced called save_save_post_{$post_type}
to make things easier. This hook is also recommended by the ACF forum to update custom fields.