首頁  >  問答  >  主體

將在WordPress中建立貼文後,將貼文ID儲存到會話變數中

我新增了一個操作掛鉤,以便在儲存貼文後我會將貼文的資訊儲存到會話變數中。

在我的 php 檔案的開頭新增: session_start()

然後我有:

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 );

我還建立了另一個函數,用於檢查會話中儲存的變數並檢查 post_id 是否已定義,然後我將繼續顯示帶有訊息的 div,如下所示:

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 
    }
}

在檔案最後我呼叫函數:check_new_post_saved();

#在我嘗試在 WordPress 中建立並保存貼文後 - 它保存正確,但是當我在開發工具中檢查會話儲存時,我沒有看到任何變數。我不確定我做錯了什麼。

P粉806834059P粉806834059177 天前330

全部回覆(1)我來回復

  • P粉810050669

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

    儲存貼文後執行的掛鉤名稱為 wp_insert_post

    #

    回覆
    0
  • 取消回覆