Set ACF default values for existing posts.

I recently ran into an issue where I needed to add a true/false option to a page template. Setting this up was super easy, but the concern came up of what to do about the previous content?

Of course, I did the usual Googling and came across this solution on stackoverflow.   Depending on how many posts and/or pages you are trying to use this on, performance could be an issue if you’re on shared hosting ( updating numerous fields across thousands of pages ).

I’ve copied and pasted the function below for reference.  I tested this out on several instances to cross reference edits and it worked flawlessly.  That being said, when you’re updating data like this you should always be careful.  Create a DB backup before you let loose!

This function also runs as soon as you access the admin, so you’ll want to remove it after you’re done so you aren’t running it over and over again.

add_action('admin_init', 'set_default_acf_values');

function set_default_acf_values() {

    $args = [
        'post_type'      => 'page',
        'posts_per_page' => -1,

    $posts = get_posts($args);

    foreach($posts as $post) {
        if (empty(get_field('your_field_name_here', $post->ID))) {
            update_field('your_field_name_here', 0, $post->ID);
            // print_r($post->post_title);echo '<br/>';
        } else {
            // print_r($post->post_title);echo '<br/>';