Home Forums Backend Issues (wp-admin) Advanced Custom Fields and JSON


Advanced Custom Fields and JSON

  • Hello guys, I got seriously stuck and strongly hope for your help.

    What I need is to write data from a certain custom field in .json file each time a post published or updated. Here’s my code in functions.php:

    function opt_update($ID, $post) {
        $args = array(
            'post_type' => 'post'
        $opt_array = array();
        $the_query = new WP_Query($args);
        while ($the_query -> have_posts()): $the_query -> the_post();
        array_push($opt_array, array(
            'price' => get_field('price')
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/wp-content/themes/blablabla/json/data.json', raw_json_encode($opt_array));
    add_action('publish_post', 'opt_update', 10, 2);

    The problem is that my script saves the data I want… but only if I press the ‘Update’ button for the second time. For example, if I publish a post with ‘123’ in the ‘price’ field, it will write {“price”:false} firstly and {“price”:”123″} at the second time… if I change value in the custom field to ‘123456’, it’ll be still {“price”:”123″} for the first time and will be updated to {“price”:”123456″} after the second click.
    Where am I wrong?

  • Try using the acf/save_post hook with a priority of 20. This will run after all of the data is saved. You will need to make some changes to your function.

  • Thank you, works perfectly!

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

The topic ‘Advanced Custom Fields and JSON’ is closed to new replies.