Home  >  Q&A  >  body text

After creating a post in WordPress, save the post ID into a session variable

I added an action hook so that after saving the post I would store the post's information into a session variable.

Add at the beginning of my php file: session_start()

Then I have:

function save_post_in_session( $post_ID, $post ) {
    $_SESSION['post_id'] = $post_ID;
    $_SESSION['post_title'] = $post->post_title;
}

add_action( 'created_post', 'save_post_in_session', 10, 2 );

I also created another function that checks the variables stored in the session and checks if the post_id is defined, then I will proceed to display the div with the message like this:

function check_new_post_saved() {
    if( isset( $_SESSION['post_id'] ) ) {
    ?>
        <div class='custom-alert' id='comment_custom_alert'>
                <div class='alert-success'>
                    <button type='button' onclick='this.parentNode.parentNode.remove()' class='close'>&times;</button>
                    <strong>Success!</strong> Your post has been saved successfully.
                </div>
            </div>
    <?php 
    }
}

At the end of the file I call the function: check_new_post_saved();

After I try to create and save the post in WordPress - it saves correctly, but when I check the session storage in the dev tools, I don't see any variables. I'm not sure what I'm doing wrong.

P粉806834059P粉806834059227 days ago373

reply all(1)I'll reply

  • P粉810050669

    P粉8100506692024-03-29 00:01:48

    The hook that runs after saving the post is named wp_insert_post

    reply
    0
  • Cancelreply