How to access the post ID after a post is created

Created by Phil Kurth, Modified on Fri, 01 Jul 2022 at 02:20 PM by Phil Kurth

You may have a situation where you need the newly created or edited post ID. When Advanced Forms creates/updates a post, it adds the post ID to the core submission object under the `post` key. e.g; 

$post_id = AF()->submission['post']

You can access this anywhere after the post editing has run.


Will this affect a field of the same name?

No. If you have a field of the same name it will not be affected and you can continue using af_get_field( 'post' ) to access that field value in your submission handler.


Accessing the post ID in a custom submission handler

Post editing/updating is a built-in submission handler that runs on a priority of 10 so you may use a custom submission handler with a priority greater than 10. e.g; 

add_action( 'af/form/submission', function ( $form, $fields, $args ) {

  if ( isset( AF()->submission['post'] ) ) {
    $post_id = AF()->submission['post'];

    // Use the post ID here …
    
  }

}, 20, 3 ); // Note the priority of 20 here.


Using specific hooks for post creation and post update

If you only need to run code specifically when a post is created but not updated (and vice versa) there are some more specific hooks available to you. Note that the priority of these hooks is not important as these are fired as part of the post editing submission handler. 

add_action( 'af/form/editing/post_created', function ( $post, $form, $args ) {

  // Run code for the newly created $post_object.
  $post_id = $post->ID;

}, 10, 3 );
add_action( 'af/form/editing/post_updated', function ( $post, $form, $args ) {

  // Run code for the updated $post_object.
  $post_id = $post->ID;

}, 10, 3 );

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select atleast one of the reasons

Feedback sent

We appreciate your effort and will try to fix the article