Support

Account

Home Forums General Issues Function that get ACF fields value before saving

Solving

Function that get ACF fields value before saving

  • Ok, first of all I found a similar question HERE but more than 2 hours I’m trying to use it with my function with no success.

    I have a function that relay on my acf checkbox field. It is working fine but I have to update the post twice, because get_field(‘checkbox_field’) returns the data after the other content.

    Here is an example:

    add_filter('wp_insert_post_data', 'my_func');
    function my_func($post) {
        $pageID = 123; // certain page id
        $cp_field = get_field("custom_field", $pageID);
        if ($post['post_type'] != 'my_post_type'
            || $post['post_status'] == 'trash'
        )
            return $post;
    
        if(!get_field('checkbox_field')) { // The problem field
            // ... do something here
            return $post;
        } else {
            return $post;
        }
    }

    Any help would be greatly appreciated.

  • Hi @gani

    The get_field function is retuning the data which is already saved, this is because your code is running BEFORE acf has saved the data.

    To run your code AFTER acf has saved, hook into the acf/save_post action (checkout the docs for more info). be sure to add the action with a priority AFTER 10.

    Thanks
    E

  • I find the info in the docs, but can’t understand how to use it. Could you explain a bit more?

  • Hi @gani

    You are using a filter called add_filter('wp_insert_post_data', 'my_func');.
    Please change this to add_action('acf/save_post', 'my_func');.

    You can then change the priority (please read docs on the add_action function)

    Thanks
    E

  • i have similar problems but i have any results. i would like update the slug (post_name) with wp_insert_post_data based on my field my_baseline

    Step 1
    – Create new post
    – fill field text as “my_baseline”

    Step 2
    – Save your post

    i finaly found simple solution to use $_POST[‘acf’][‘field_myfieldid’];
    the better way with to use json to convert acf_field name to acf_field_id

Viewing 5 posts - 1 through 5 (of 5 total)

The topic ‘Function that get ACF fields value before saving’ is closed to new replies.