How to Update Custom Fields with Default Values For Existing Posts when using ACF

Let’s take a scenario where there are 10 Pages in a WordPress site.

You proceed to create a Text-type of custom field called, say, “Custom Title” using ACF for Pages and set its default value to “This is the default value” (not the most practical, but just to illustrate…).

When a new post (of the post type to which the field group is attached) is added and the field is left empty, the Custom Title post meta will be created and updated with the default value after the Publish button is clicked.

What about the existing Pages?

Unfortunately, the post meta does not exist for them and hence the default value does not appear.

Unless you edit each of those 10 Pages manually and click the Update button.

This is not a problem with a few posts, but what if there are 100s of posts?

This Pro tutorial shows how we can loop through the posts (Pages, in this example) for which our custom field is empty and update the field for each.

Step 1

Edit your field group.

Click on Screen Options.

Tick Field Keys.

Note the field key value. We need this in the next step.

Step 2

Add the following in child theme‘s functions.php (w/o the opening PHP tag) or a code snippets plugin:

<?php 

// Loop through all Pages and update post meta with the value of custom_title ACF custom field.
add_action( 'init', function () {
	// makes the code below this run only once
	if ( did_action( 'init' ) >= 2 ) return;

	$args = [
		'post_type' => 'page',
		'posts_per_page' => -1,
		'meta_query' => [
			[
				'key' => 'custom_title',
				'compare' => 'NOT EXISTS'
			]
		],
	];

	$pages = get_posts( $args );

	foreach ( $pages as $page ) {
		$custom_title = get_field( 'field_65b4c9ba66c1f', $page->ID );

		update_field( 'custom_title', $custom_title, $page->ID );
	}
} );

Replace field_65b4c9ba66c1f with the field key from the previous step.

Make other changes as needed, like the post type and custom field name.

Visit any page in the site and check any of your existing posts (Pages, in this example). The custom field will be added for each and filled with the default value.

You can go ahead and delete/disable the code after the task is done.

References

https://support.advancedcustomfields.com/forums/topic/force-default-value-on-existing-posts/#post-126430

https://support.advancedcustomfields.com/forums/topic/how-to-retrieve-field-type-keys-and-default-values/#post-126225