Steve Taylor photo

When a post is first published, but not when it’s re-published

I’ve just been looking into some WordPress code that needs to run only when a post is first published.

WordPress provides a number of hooks for post status transitions. You’d think the one to use would be post_publish. However, testing shows that this also fires when a post is updated. Also, consider the scenario where an editor sets a post back to draft, then re-publishes. Do you also want the code to run then?

In order to fully control things, it seems you need to use transition_post_status. You can compare the post_date, which is stamped when the post is first published then never changed, to the post_modified, which is stamped every time a post is edited.

add_action( 'transition_post_status', 'pilau_publish_post', 10, 3 );
function pilau_publish_post( $new_status, $old_status, $post ) {
	if ( get_post_type( $post ) == 'post' && $new_status == 'publish' && $post->post_date === $post->post_modified ) {
		// do some stuff when a post is first published...
	}
}

One comment

Leave a comment

Your email address will not be published. Required fields are marked *