looping through pages and updating ACF field data for each inside of a function

having a bit of an issue and hoping for some help. Basically I am triggering a function on acf/save_post action for a custom post type called 'settings'. So if 'settings' is saved or updated I want to loop through all existing pages and update a ACF field for each page with a specific piece of data. My loop is below. I've been fighting with this thing all weekend but it doesn't seem to update any pages. Any help would be huge! Thanks!

` $the_query = new WP_Query( array( 'post_type' => 'page' ) );

        while ( $the_query->have_posts() ) : $the_query->the_post();
            global $post;  
             $pageID = $post->ID;
                    update_field('temp_post_data','test' , $pageID);
        endwhile;`

1 answer

  • answered 2021-09-27 07:22 Martin Mirchev

    You are trying to update field on current page.

    Try this

    function my_custom_function() {
      $pages = get_pages(); // get all pages
      foreach($pages as $page):
        // error_log($page->ID); // debug if needed
        update_field('temp_post_data','test' , $page->ID); //for each page we are updating  field
      endforeach;
    }
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum