publish_postaction-hookWP 2.3.0

Fires when a post (a post of the post type) is published or updated, allowing an action to be performed.

This hook fires every time, NOT only when a post is published. It fires:

  • When a post first transitions to the published (publish) status from another status.
  • When an already published post is subsequently updated.

wp_insert_post() always calls this hook. Therefore, when an action should be performed only once, when a post is published (not updated), use:

  • Hooks from the (old_status)_to_(new_status) family:

    • new_to_publish - when a new post is first published, for example, when it is added by wp_insert_post().
    • auto-draft_to_publish - when a new post is first published from the WordPress admin area.
    • draft_to_publish - when a saved post is published.
    • future_to_publish - when a scheduled post is published.
  • Or transition_post_status, which fires whenever a post is updated or its status changes.

For pages (posts of the page type), this hook is named publish_page. For attachments, it is publish_attachment, and so on.

This is one of the variants of the dynamic hook (new_status)_(post_type)

Usage

add_action( 'publish_post', 'wp_kama_publish_post_action', 10, 3 );

/**
 * Function for `publish_post` action-hook.
 * 
 * @param int     $post_id    Post ID.
 * @param WP_Post $post       Post object.
 * @param string  $old_status Old post status.
 *
 * @return void
 */
function wp_kama_publish_post_action( $post_id, $post, $old_status ){

	// action...
}
$post_id(int)
The post ID.
$post(WP_Post)
The WP_Post post object.
$old_status(string) (WP 5.9.0)
The old post status.

Examples

#1 Perform an action for a published post

This example shows how to perform an action when a post is published or updated with the publish status:

add_action( 'publish_post', 'publish_post_action', 10, 2 );

function publish_post_action( $post_id, $post ){

	// Do something when the post is published
}

Changelog

Since 2.3.0 Introduced.
Since 5.9.0 Added $old_status parameter.

Where the hook is called

wp_transition_post_status()
publish_post
wp-includes/post.php 5980
do_action( "{$new_status}_{$post->post_type}", $post->ID, $post, $old_status );

Where the hook is used in WordPress

wp-includes/default-filters.php 295
add_action( $action, '_delete_option_fresh_site', 0 );
wp-includes/default-filters.php 447
add_action( 'publish_post', '_publish_post_hook', 5, 1 );