TechEarl

How to Update ACF Fields Programmatically

update_field() is the canonical way to write ACF data programmatically: the signature, Repeater and Flexible Content writes, field keys vs names, options pages and user meta, ACF vs native post meta in wp_postmeta, the gotchas, and safe bulk updates with AI and WP-CLI.

Ishan KarunaratnePublished ⏱️ 15 min readUpdated
Share thisCopied
Guide to ACF update_field(): signature, Repeater and Flexible Content writes, field keys, options pages, user meta, and safe bulk updates with WP-CLI.

update_field() is the canonical way to write ACF data programmatically from PHP. It works for every field type ACF supports, on posts, users, taxonomy terms, options pages, and comments. The function signature is simple but the right value shape varies by field type, and a few gotchas will trip you up on Repeater and Flexible Content writes. After many years of running data-migration scripts against ACF fields on directory sites at scale, here is the canonical reference, plus the workflow I use when an AI assistant writes the bulk-update script and WP-CLI runs it.

Jump to:

The function signature

php
update_field( $selector, $value, $post_id );
  • $selector (string): the field name OR the field key (field_abc123).
  • $value (mixed): the value to write. Shape depends on the field type.
  • $post_id (mixed): the post ID, or 'option', 'user_42', 'term_5', 'comment_99'.

Returns true on success, false on failure. The function will create the meta entry if it does not exist.

Simple field types: text, number, boolean, select

The straightforward cases:

php
update_field( 'hero_heading', 'Welcome to the site', $post_id );
update_field( 'view_count', 1024, $post_id );
update_field( 'featured', true, $post_id );
update_field( 'priority', 'high', $post_id );      // select field
update_field( 'tags', ['blue', 'green'], $post_id ); // multi-select / checkbox

The text, textarea, and wysiwyg fields all accept strings. Numbers accept numeric values. True/False accepts booleans. Single-select fields accept the option value as a string. Multi-select and checkbox fields accept arrays of option values.

These accept the WordPress attachment ID regardless of the field's "Return Format" setting:

php
update_field( 'hero_image', 42, $post_id );          // image field
update_field( 'brochure_pdf', 99, $post_id );        // file field
update_field( 'gallery', [42, 99, 173, 256], $post_id ); // gallery field

The return format only affects how get_field() hydrates the stored value when reading. Storage is always the attachment ID. See ACF Image Field Returning an Array Instead of a URL? for the read-time return-format details.

Repeater fields

Repeater values are arrays of arrays. The outer array represents rows; each inner array maps sub-field names to values:

php
$team = [
    [
        'name'  => 'Alex Chen',
        'role'  => 'Lead Engineer',
        'photo' => 42, // attachment ID
    ],
    [
        'name'  => 'Sam Patel',
        'role'  => 'Designer',
        'photo' => 99,
    ],
];

update_field( 'team_members', $team, $post_id );

The sub-field names in the inner arrays must match the sub-field names registered in the field group. A typo silently writes nothing for that sub-field.

To append a row to an existing Repeater rather than overwriting:

php
$existing = get_field( 'team_members', $post_id ) ?: [];
$existing[] = [
    'name' => 'Jordan Lee',
    'role' => 'Project Manager',
    'photo' => 173,
];
update_field( 'team_members', $existing, $post_id );

ACF also provides add_row() which appends a single row without the read-then-write dance:

php
add_row( 'team_members', [
    'name' => 'Jordan Lee',
    'role' => 'Project Manager',
    'photo' => 173,
], $post_id );

Flexible Content fields

Flexible Content values are arrays of arrays, with each inner array including an acf_fc_layout key naming the layout:

php
$page_builder = [
    [
        'acf_fc_layout' => 'hero',
        'heading' => 'About our work',
        'subheading' => 'Custom WordPress development since 2011',
    ],
    [
        'acf_fc_layout' => 'cta',
        'heading' => 'Start a project',
        'button_label' => 'Get in touch',
        'button_url' => '/contact',
    ],
    [
        'acf_fc_layout' => 'stat_row',
        'stats' => [
            ['label' => 'Sites shipped', 'value' => '120', 'unit' => '+'],
            ['label' => 'Years operating', 'value' => '15', 'unit' => ''],
        ],
    ],
];

update_field( 'page_builder', $page_builder, $post_id );

The acf_fc_layout value must match a layout name registered in the field group. The sub-field names inside each layout block must match that layout's sub-field registration. Nested Repeater data (like the stats array inside stat_row) follows the same array-of-arrays structure.

Relationship and Post Object fields

These accept arrays of post IDs (for Relationship) or a single post ID (for Post Object):

php
update_field( 'related_posts', [10, 20, 30], $post_id );    // relationship
update_field( 'featured_post', 42, $post_id );              // post object

The order of IDs in the array is preserved as the relationship order. For deep coverage of relationship-field write gotchas, see Why ACF Relationship Fields Lose Their Selected Order.

Writing to options pages and user meta

The third argument changes context. For options pages, pass 'option':

php
update_field( 'site_announcement', 'Holiday hours in effect', 'option' );
update_field( 'footer_links', [...], 'option' );

For user meta:

php
update_field( 'bio', 'Senior WordPress developer', 'user_42' );
update_field( 'social_links', [...], 'user_' . $user_id );

For taxonomy term meta:

php
update_field( 'featured_image', 99, 'term_5' );
update_field( 'description_long', '...', 'category_5' ); // works with taxonomy name too

Field keys vs field names

update_field() accepts either the field name (hero_heading) or the field key (field_abc123def456). The field key is preferred for code that runs before ACF has fully initialized (very early hooks, REST API callbacks) because it does not require ACF to do the name-to-key lookup.

To find a field's key: export the field group from Custom Fields > Tools > Export Field Groups, or inspect the field in the admin UI (the key shows under the field name in edit mode).

php
update_field( 'field_abc123def456', 'New heading', $post_id );

For most application code running during normal WordPress requests, the field name is fine. For mu-plugin code that runs very early, use the key. The full reference is in ACF's Field Keys documentation.

ACF fields vs native post meta

ACF and native post meta are not two storage systems. Both write to the same wp_postmeta table, one row per key. The real choice is who edits the value and how much structure you want around it, and getting it wrong is how a bulk script overwrites an ACF field so the admin shows one thing and the front end another.

Native meta and register_post_meta

Native meta needs no setup:

php
update_post_meta( 42, 'price', 19.99 );
$price = get_post_meta( 42, 'price', true ); // true = return the single value, not an array

The value is stored as a string (WordPress serializes arrays and objects), with no type, no validation and no admin UI beyond the flat Custom Fields metabox. Since WordPress 4.9.8, register_post_meta declares the key (it wraps register_meta, whose array-arguments form dates from 4.6) so it gets a type, optional sanitization and, with show_in_rest, a REST API entry. It still adds no UI:

php
add_action( 'init', 'te_register_product_meta' );

function te_register_product_meta(): void {
	register_post_meta( 'post', 'price', array(
		'type'              => 'number',
		'single'            => true,
		'show_in_rest'      => true,
		'sanitize_callback' => function ( $value ) {
			return round( (float) $value, 2 );
		},
		'auth_callback'     => function () {
			return current_user_can( 'edit_posts' );
		},
	) );
}

That is the right tool when only code writes the field: a derived value, an import target, a plugin flag.

Where ACF puts the value

ACF adds the editing UI: a field group attached to a post type renders labelled inputs, selects, date and image pickers, and (in Pro) repeaters and flexible content.

The ACF field group editor in WordPress admin, defining a Product Details group with a Price number field attached to the post type
An ACF field group: a labelled Price field attached to posts. This is the editing UI native meta never gives you.

update_field( 'field_te_price', 19.99, 42 ) writes two rows to wp_postmeta: price → 19.99 (the value) and _price → field_te_price (a reference to the field definition). That underscore twin is how ACF knows which definition a value belongs to, which is what powers return-format conversion. Pass the field key, not the name, when the post has no value yet: ACF's docs say the key is what lets it create that reference row. Once the twin exists, update_field( 'price', ... ) by name works for later updates:

A terminal running wp post meta list, showing both a price row and a hidden underscore price row that references the ACF field key
wp post meta list on an ACF-managed field: the value (price) and ACF's reference twin (_price).

The reference is itself a row. ACF stores each field definition as a post in wp_posts with post_type = acf-field, the key in post_name and the whole configuration serialized into post_content:

Two queries against wp_posts for field_te_price: the first resolves it to post ID 5011, an acf-field titled Price with parent 5010; the second selects post_content and pipes it through php unserialize and jq, printing the field definition as JSON with type number, instructions Retail price in USD, required false, and prepend dollar sign
field_te_price is post 5011 (an acf-field, child of group 5010). Its post_content is the serialized field definition; unserialized through jq it is plain config: type number, the instructions, prepend $.

So the chain is value (price) → reference (_price = field_te_price) → definition (type, prepend, instructions, return format). get_field reads that definition to turn a stored Ymd date into a string in the field's return format (build a DateTime yourself with DateTime::createFromFormat() if you need one) or a stored ID into a WP_Post; get_post_meta skips the lookup and returns the raw stored value. The key is readable here because I authored it as field_te_price; a field created in the ACF UI gets an auto-generated one like field_64f3a2b1c9d8e.

The read/write rule

If a field is managed by ACF, write to it with update_field, not update_post_meta.

update_post_meta( 42, 'price', 25 ) changes the price row and leaves _price alone, which is usually fine when the field already exists. But if the row does not exist yet, writing price without _price leaves a value ACF does not recognize, so get_field may not apply its return format and the admin UI can misbehave. That is the caveat on the bulk-import tip under Gotchas that bite: update_post_meta is safe for updating existing ACF values or native keys, not for creating new ACF values. On reads, get_post_meta is fine (and marginally faster) for a raw scalar you set yourself; anything with a return format (dates, relationships, images, selects, repeaters) needs get_field.

SituationReach for
A human edits the value on the post screenACF
Repeaters, flexible content, relationship/image pickersACF (Pro for repeaters/flexible)
A derived or computed value only code ever writesregister_post_meta
An import or sync target a script populatesregister_post_meta, or update_field if editors also touch it
You need the field in the REST API with a typeregister_post_meta with show_in_rest
A throwaway flag with no UI and no editorplain update_post_meta

Gotchas that bite

The function exists check. If ACF is deactivated or not yet loaded, update_field() does not exist. Code that runs unconditionally on init or earlier should guard:

php
if ( function_exists( 'update_field' ) ) {
    update_field( 'foo', 'bar', $post_id );
}

Object cache invalidation. If your site uses a persistent object cache, the meta value written by update_field() may not appear in subsequent get_field() calls in the same request without explicit cache invalidation. ACF handles this internally in most cases, but custom caching layers in front of wp_postmeta may not.

The Flexible Content layout name must exist. If you write a Flexible Content row with acf_fc_layout set to a layout name that does not exist in the field group registration, the row writes but renders as nothing because the template loop will not match it.

Repeater sub-field key collisions. Two sub-fields in the same Repeater cannot have the same name. Even across nested Repeaters in different layouts, ACF will store data correctly but get_sub_field() reads in the inner context can become ambiguous if names overlap.

Save hooks fire on programmatic writes. update_field() triggers acf/save_post actions. If you have a hook that does expensive work on save, calling update_field in a tight loop can be slow. For bulk imports, consider update_post_meta() directly (which bypasses ACF's hook layer) and only call update_field when the ACF-specific behavior is needed.

For agency-scale ACF migration patterns, see the AI and WP-CLI workflow below and Using AI with WP-CLI for Faster WordPress Operations. For safe acf/save_post patterns, see Useful Things You Can Do with acf/save_post.

Bulk update ACF fields with AI and WP-CLI

For bulk content updates across thousands of posts, I let an AI assistant write the update_field() script and WP-CLI run it, with me approving in between. It turns a careful afternoon into about twenty minutes. Used carelessly, the same stack rewrites thousands of field values in minutes and the rollback is "restore from backup, hope you have one."

Every update follows the same three stages:

  1. Describe the goal in plain language, with constraints, edge cases and the expected outcome.
  2. The AI proposes a script: a wp eval-file script, a custom WP-CLI command class, or a sequence of wp invocations, always with --dry-run support.
  3. I read the code, run the dry run, check the output, then approve the real run. The AI never writes to production. Staging takes the agentic loop; production goes through a code-reviewed deploy (more in Using AI with WP-CLI for Faster WordPress Operations).

A schema-aware update_field prompt

The most common job is deriving one field from another across every post of a type:

text
Write a WP-CLI script that:
- Iterates every "listing" post.
- Reads the ACF field `address_state` (a text field with the full state name).
- Maps it to the two-letter postal code using a hardcoded lookup table.
- Writes the result to a new ACF field `address_state_code`.
- Leaves `address_state` untouched.
- Supports --dry-run that logs the planned change without writing.
- Logs each affected post ID with before -> after.
- Outputs a summary at the end.

Do not run it. Save to /tmp/migrate-state-codes.php and print
the invocation command.

The output uses update_field() with the right value shape per field type, as in the sections above. A script that took 90 minutes to write and test by hand takes about 15 including review.

The same prompt shape covers the other jobs I hand off:

  • Content rewrites (for example a tighter short_description, max 240 characters, generated through the Anthropic API): the script writes to a holding field such as short_description_pending, stops after a chunk of 50 posts, and logs ID, before and after length and a preview. An editor approves each value before it reaches the live field. Never auto-publish generated text.
  • Image alt-text backfills: find attachments with empty _wp_attachment_image_alt, generate descriptive alt text from the image plus its title and caption, skip obvious decoratives (icons, spacers, logos), and output a CSV of post ID, filename and generated alt for review. Writing to a pending key such as _generated_alt_pending first keeps the same approval loop. The ACF side of alt text is in ACF image alt-text handling.
  • Data normalization: for example strip a phone field to digits, format 10 digits (or 11 starting with 1) as +1-XXX-XXX-XXXX, and log anything else as "needs review". Deterministic, but the dry run still catches the edge cases the prompt missed.
  • Flexible Content layout migrations: convert every old_hero row to hero_v2 with explicit sub-field mappings (heading_text to heading, sub_text to subheading, cta to a Group with cta.label and cta.url), leave other layouts untouched, and write page_builder back with update_field(). This is the most error-prone job because the data is nested; a script that silently drops sub-fields can destroy years of content, so read that dry-run output line by line.

Safety rules for AI-written migrations

  • Snapshot before write. The first line of every migration is wp db export - | gzip > /backups/pre-migration-$(date +%Y%m%d).sql.gz (wp db export writes plain SQL and does not compress a file just because its name ends in .gz, so the dump goes to STDOUT and through gzip). The rollback decompresses it back into WP-CLI: gunzip -c /backups/pre-migration-YYYYMMDD.sql.gz | wp db import -.
  • --dry-run on every script. I do not accept a script without one.
  • Staging first, always, even when staging is out of sync and the script looks obviously safe.
  • Holding fields for generated text. Stage to a parallel field and review before anything user-facing changes.
  • Chunk large operations. For 50,000 posts, batches of 100 to 500 with a checkpoint between them, so a PHP timeout cannot leave the database half migrated.
  • Log every write: field, post, old value, new value.
  • No production credentials for the agent. It can SSH to staging; production changes go through the normal pull request and CI pipeline.

What I will not delegate at all: direct production updates, wp db reset, wp db drop, wp site empty or anything equally destructive, user deletion at scale, anything touching authentication, payment or PII without line-by-line review, and auto-publishing generated content to user-visible fields.

AI removes the typing. It does not remove the judgment about whether a migration is correct, what the edge cases are, or whether the dry-run output looks right. For the wider agency picture, see How Small WordPress Agencies Can Use AI in 2026, by Role and Using Claude CLI to Manage WordPress Sites.

For post fields, no. ACF writes the value and a reference twin (the underscore-prefixed key) into wp_postmeta, the same table native meta uses. Options-page fields go in wp_options, and user/term fields go in their respective meta tables, but the storage is always WordPress's native meta, never a separate ACF table.

Yes for a raw scalar like a number or a short string, the value is right there in the meta row. But for any field with a return format (date, image, relationship, select, repeater) get_post_meta gives you the raw stored value, while get_field applies ACF's formatting and hands back the object you actually want.

You can call update_post_meta with no registration at all. register_post_meta is what adds a type, a sanitize callback, and REST exposure, so it is worth doing for any meta key your code relies on. It does not add an admin UI either way, that is ACF's job.

Whichever owns the field. If the field is an ACF field a human also edits, use update_field so the value and its reference twin stay consistent. If it is a native meta key only code writes, update_post_meta is leaner. Don't mix the two writers on the same key.

Sources

Authoritative references this article was fact-checked against.

TagsWordPressACFWP-CLIMigrationsAIPost MetaCustom Fields

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts

Map Gravity Forms submissions to ACF fields, including Repeater rows: the gform_after_submission hook, field mapping, JSON rows, and the plugin path.

How to Populate ACF Fields from Gravity Forms

Gravity Forms can create WordPress posts on submission, but mapping form fields to ACF fields requires a hook. The canonical pattern uses gform_after_submission to call update_field. Plus three patterns for sending form data into ACF Repeater rows, and the plugin path.

Write an effective system prompt in five parts: role, capabilities, constraints, output, refusal. Plus anti-hallucination tactics and evals for regressions.

How to Write an Effective System Prompt

Write an effective system prompt for an LLM with five parts: role, capabilities, constraints, output format, refusal policy. With before/after examples, the structure that maximises cache hits, six techniques that stop an LLM from hallucinating, and the evals that catch prompt regressions in CI.