How to catch wordpress post ID when it’s published

To put it briefly, WordPress hooks let you modify parameters or output of functions (filters) or execute custom code when something happens (actions). Both types of hooks usually pass one or more arguments to the callback functions that are attached to them.

During a page request WordPress goes through series of steps to get the page rendered. There’s a nice summary of the actions that run during a typical request on the old Codex. To have your custom code run at the correct step, you need to add the callback to the action or filter before it runs.

WordPress uses wp_insert_post() to insert and update posts in the database. When looking at the function’s source code on Trac, you can see there are bunch of apply_filters and do_actions inside it. The former is for calling the filtering callbacks and the latter for action callbacks.

For example you can see that the last do_action is wp_insert_post with three parameters – $post_ID, $post, $update. You can either read the comments on the source code or have a look at the action’s documentation page to learn more about it.

Basic example how to use an action hook,

add_action( 'wp_insert_post', 'example_wp_insert_post', 10, 3 ); // hook, callback, priority, # of accepted args
function example_wp_insert_post( int $post_ID, WP_Post $post, bool $update ) {

  // is the post new or was this an update?
  if ( $update ) {
    // don't do anything
    return;
  }

  // was the post published?
  if ( 'publish' !== $post->post_status ) {
    // bail
    return;
  }

  // do something with ID and/or post..
  
}

One thing to notice is that wp_insert_post() returns post ID on success. So if you use it somewhere in your code, then you don’t have to bother with hooks – just use the return result directly!

// somewhere in your code
$new_post_id = wp_insert_post( $postarr, $wp_error );
if ( ! is_wp_error( $new_post_id ) ) {
  // do something with the new post's ID
}