After creating a post in WordPress, save the post ID into a session variable
P粉806834059
P粉806834059 2024-03-28 12:36:37
0
1
417

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粉806834059
P粉806834059

reply all(1)
P粉810050669

The hook that runs after saving the post is named wp_insert_post代码>

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template