Skip to content

Saving post id into a session variable after creating a post in wordpress

I am adding an action hook so that after i save a post i will store the information of the post into session variables.

In the beginning of my php file i added: session_start()

I then 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 create another function for the purpose of checking the stored variables in session and checking if post_id is defined then i will go ahead and display a div with a message as follows:

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.

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

After i try creating and saving a post in wordpress – it saves properly but when i check my session storage in my devtools i am not seeing any variables. I am not sure what i am doing wrong.



The hook that is run after the post was saved is named wp_insert_post

User contributions licensed under: CC BY-SA
2 People found this is helpful