Forum Replies Created

Viewing 4 replies - 1 through 4 (of 4 total)
  • Thread Starter Lzhelenin

    (@lzhelenin)

    Tried to do it with general wordpress posts and simplier code… still writes the file only after I press the ‘update’ button the second time

    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')
        ));
        endwhile;
        wp_reset_postdata();
        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);

    Thread Starter Lzhelenin

    (@lzhelenin)

    What I found out is that the function DOES write the file. But only if I:

    1. Change the title of the custom post

    Or

    2. Press ‘update’ button two times. For example, if I change number in a custom field to ‘123’ and press the ‘update’ button, then change it to ‘1234’ and press the button again, after the second time it’ll write ‘123’ value in the file.

    Thread Starter Lzhelenin

    (@lzhelenin)

    Thanks Navneil, but can’t find solution in the articles… tried to do it with ‘transition_post_status’, but everything is the same

    <?php
    add_action('transition_post_status', function($new_status, $old_status, $post)
    {
    
        if ('publish' == $new_status && $post->post_type == 'opt') {
    
            $args      = array(
                'post_type' => 'opt'
            );
            $opt_array = array();
            $the_query = new WP_Query($args);
            sleep(3);
            while ($the_query->have_posts()):
                $the_query->the_post();
                $good_type_array = array();
                while (have_rows('good_type')):
                    the_row();
                    $good_type_name = get_sub_field('good_type_name');
                    array_push($good_type_array, $good_type_name);
                endwhile;
                array_push($opt_array, array(
                    'name' => get_the_title(),
                    'good_type' => $good_type_array,
                    'price' => get_field('price')
                ));
            endwhile;
            wp_reset_postdata();
            file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/wp-content/themes/blablabla/json/data.json', raw_json_encode($opt_array));
        }
    }, 10, 3);
    ?>

    Thread Starter Lzhelenin

    (@lzhelenin)

    Solved

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