Post publish only hook?

The {$old_status}_to_{$new_status} and {$new_status}_{$post->post_type} hooks tend to generally solve the problem.

To avoid running the code in case post status is changed to draft then published again (after already being published), implement a simple flag using the post_meta functionality.

Note: the updated hook should be ‘draft_to_publish’ instead of ‘draft_to_published’ however, the code below is not modified and should be if you plan to use in WP 3.5

add_action( 'draft_to_published', 'wpse47566_do_once_on_publish' );
function wpse47566_do_once_on_publish( $post ) {
    // check post type if necessary
    if ( $post->post_type != 'a_specific_type' ) return;

    $post_id = $post->ID;

    if ( !get_post_meta( $post_id, 'mycoderan', $single = true ) ) {
        // ...run code once
        update_post_meta( $post_id, 'mycoderan', true );
    }
}

Leave a Comment