Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    (@bcworkz)

    The block editor saves data a little strangely. The content is saved separately via an API request. The other data is saved through the traditional post.php route. Thus your checkbox status has been separated from the saving of content. Both requests eventually go through “save_post”, but not at the same time. When you attempt to get content, due to a race condition, it’s not yet available, or it’s stale data.

    I cannot offer a good solution, but at least now you know what you’re up against. BTW, a better hook for altering post data is ‘wp_insert_post_data’ because it fires before the data is inserted into the DB.

    Thread Starter Juliano

    (@incognijm)

    I will try to see if I can do something with wp_insert_post_data. What people normally do to change/work with the post content using some kind of post meta or other variables in the post?

    Also, is there a better way to debug this kind of code besides a var_dump/exit and check the network?

    Thanks!

    Thread Starter Juliano

    (@incognijm)

    @bcworkz thanks for the answer and about the hook ‘wp_insert_post_data‘. I changed the code as follows and now it works:

    add_action( 'save_post', 'ac_save_meta' );
    add_filter( 'wp_insert_post_data', 'ac_check_links',10,2);
    
    function ac_check_links($data, $postarr) {
        if (!empty($postarr['ac_link_checkbox']) && $postarr['ac_link_checkbox'] != "no") {
            $data['post_content'] = ac_remove_links( $data['post_content'] );
        }
        return $data;
    }
    
    function ac_save_meta($post_id) {
        update_post_meta( $post_id, 'ac_link_checkbox', $_POST['ac_link_checkbox']);
    }

    Is this the correct way to deal with changes in the content while saving?

    Moderator bcworkz

    (@bcworkz)

    Looks good! That turned out to be easier than I thought it would be 🙂

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘if statement not working in save_post’ is closed to new replies.