Bulk Translating ACF (Advanced Custom Fields) WYSIWYG HTML Fields Safely
Use wp eval to export raw Advanced Custom Fields (ACF) WYSIWYG values, translate the editable text in their HTML, and write approved results to existing localized posts with update_field(). This workflow covers top-level WYSIWYG fields stored as post metadata; the main production caveat is that a valid post ID and field key don’t prove that the post belongs to the intended language.
Keep the translation handoff separate from the write operation. A translator should be able to revise a paragraph without touching post IDs, field keys, shortcodes, or links. An editor should be able to revise WordPress content without an older translation silently overwriting it.
Build the source-to-target map
Create and verify the localized posts in your multilingual plugin before exporting anything. For each row, take the post IDs from the plugin’s translation relationship, not from a slug match or adjacent IDs. On multisite, pin WP-CLI to the correct site: two sites can have posts with the same numeric ID. The example below uses one field key registered for both posts.
[
{
"source_id": 410,
"target_id": 782,
"field_key": "field_64f061209e2a1"
},
{
"source_id": 411,
"target_id": 783,
"field_key": "field_64f061209e2a1"
}
]
Save this as acf-map.json and replace the example IDs and key. The field key identifies the ACF definition; the field name is the metadata key derived from that definition. Verify both posts’ language assignments and confirm the field group applies to the destination in the editor.
Never import into a field configured to copy or synchronize from the source locale. Change the field to the plugin’s independent translation mode first, or a later source save can overwrite the imported text.
Decide which parts of the HTML can change
| Content | Example | Translation rule |
|---|---|---|
| Visible copy | <p>Delivery takes two days.</p> | Translate the text while keeping the paragraph and any inline markup. |
| Human-readable attributes | alt="Rear view", aria-label="Size guide" | Translate when they convey meaning; preserve deliberately empty alt="". |
| Structural identifiers | id="shipping", class="product-note" | Preserve these by default. An ID may be referenced by an anchor, CSS, or assistive technology. |
| Link destinations | href="/shipping/#returns" | Keep the original unless you have an approved locale URL and have checked its fragment. |
| Shortcodes and placeholders | [gallery ids="18,24"], {{order_id}} | Protect the literals. If a shortcode contains translatable text, handle it according to that shortcode’s documented syntax. |
Give the translator complete sentences, including any inline tags, so they can see how clauses relate. Review any movement of an inline tag: a link must still wrap the intended words, and an emphasis tag must still emphasize the right part of the sentence.
<!-- Broken: the anchor target changed and a character reference appeared as text. -->
<h3 id="entrega">Entrega</h3>
<p>Consulta <a href="/shipping/#returns">envíos &amp; devoluciones</a>.</p>
<p>[galería ids="18,24"]</p>
<!-- Fixed: preserve identifiers and shortcode syntax; encode the ampersand once. -->
<h3 id="shipping">Entrega</h3>
<p>Consulta <a href="/shipping/#returns">envíos & devoluciones</a>.</p>
<p>[gallery ids="18,24"]</p>
The broken fragment can leave existing links to #shipping with nowhere to land, and the browser displays a literal & in the link text. WordPress won’t run the renamed shortcode unless one with that name is registered. In the fixed version, check that the unchanged URL is the intended destination for Spanish readers.
Export, plan, and apply from one terminal script
Save the following as acf-bulk.sh. It requires Bash, WP-CLI, PHP 8.1 or later, and active ACF on the selected site. It rejects duplicate target fields, reads stored values without WYSIWYG formatting, and checks for edits to either side before writing. It deliberately excludes option pages, nested fields, and content stored outside normal post metadata.
# acf-bulk.sh
set -euo pipefail
if [[ $# -ne 3 ]]; then
printf 'Usage: bash acf-bulk.sh export|plan|apply input.json output\n' >&2
exit 2
fi
mode=$1
case "$mode" in export|plan|apply) ;; *) exit 2 ;; esac
: "${WP_SITE_URL:?Set WP_SITE_URL to the exact WordPress site URL}"
: "${WP_RUN_USER:?Set WP_RUN_USER to a WordPress user ID or login}"
php=$(cat <<'PHP'
function acf_bulk_meta($id, $field) {
$name = $field['name'];
$values = get_post_meta($id, $name, false);
$refs = get_post_meta($id, '_' . $name, false);
if (count($values) > 1 || (isset($values[0]) && !is_string($values[0]))) {
throw new RuntimeException("Unexpected stored value on post $id: $name");
}
if (($values || $refs) && $refs !== [$field['key']]) {
throw new RuntimeException("Missing or mismatched ACF reference on post $id: $name");
}
return [
'html' => $values[0] ?? '',
'sha' => hash('sha256', serialize([$values, $refs])),
];
}
function acf_bulk_emit($data) {
echo json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE
| JSON_UNESCAPED_SLASHES), "\n";
fflush(STDOUT);
}
try {
if (!function_exists('acf_get_field') || !function_exists('update_field')) {
throw new RuntimeException('Activate ACF on the selected site.');
}
$mode = getenv('ACF_BULK_MODE');
$rows = json_decode(stream_get_contents(STDIN), true, 512, JSON_THROW_ON_ERROR);
if (!is_array($rows) || !array_is_list($rows) || !$rows) {
throw new RuntimeException('Expected a nonempty JSON list.');
}
$seen = $jobs = [];
foreach ($rows as $index => $row) {
$source = $row['source_id'] ?? null;
$target = $row['target_id'] ?? null;
$key = $row['field_key'] ?? null;
if (!is_int($source) || !is_int($target) || $source < 1
|| $target < 1 || $source === $target || !is_string($key)
|| !str_starts_with($key, 'field_')) {
throw new RuntimeException("Invalid map entry at index $index");
}
$a = get_post($source);
$b = get_post($target);
if (!$a || !$b || $a->post_type !== $b->post_type
|| in_array($a->post_type, ['revision', 'attachment'], true)
|| in_array($a->post_status, ['trash', 'auto-draft'], true)
|| in_array($b->post_status, ['trash', 'auto-draft'], true)
|| !current_user_can('edit_post', $source)
|| !current_user_can('edit_post', $target)) {
throw new RuntimeException("Ineligible or inaccessible posts: $source / $target");
}
$field = acf_get_field($key);
if (!$field || $field['type'] !== 'wysiwyg'
|| empty($field['parent']) || !acf_get_field_group($field['parent'])) {
throw new RuntimeException("Not a top-level WYSIWYG field: $key");
}
$slot = $target . ':' . $field['name'];
if (isset($seen[$slot])) {
throw new RuntimeException("Duplicate destination: $slot");
}
$seen[$slot] = true;
$from = acf_bulk_meta($source, $field);
$to = acf_bulk_meta($target, $field);
$job = [
'source_id' => $source, 'target_id' => $target, 'field_key' => $key,
'source_sha' => $from['sha'], 'target_sha' => $to['sha'],
'source_html' => $from['html'], 'target_html' => $to['html'],
'approved_html' => $row['approved_html'] ?? null,
];
if ($mode !== 'export') {
if (($row['source_sha'] ?? null) !== $from['sha']
|| ($row['target_sha'] ?? null) !== $to['sha']) {
throw new RuntimeException("Stale export: $slot");
}
$html = $job['approved_html'];
if (!is_string($html) || trim($html) === '' || wp_kses_post($html) !== $html) {
throw new RuntimeException("Empty, unapproved, or filtered HTML: $slot");
}
} else {
$job['approved_html'] = null;
}
$jobs[] = [$job, $field];
}
if ($mode === 'export') {
acf_bulk_emit(array_column($jobs, 0));
return;
}
foreach ($jobs as [$job, $field]) {
$source = $job['source_id'];
$target = $job['target_id'];
$html = $job['approved_html'];
$event = ['target_id' => $target, 'field_key' => $field['key']];
if ($job['target_html'] === $html) {
acf_bulk_emit($event + ['status' => 'unchanged']);
continue;
}
if ($mode === 'plan') {
acf_bulk_emit($event + ['status' => 'would_write']);
continue;
}
acf_bulk_emit($event + ['status' => 'writing']);
foreach ([$source, $target] as $id) {
wp_cache_delete($id, 'post_meta');
}
if (acf_bulk_meta($source, $field)['sha'] !== $job['source_sha']
|| acf_bulk_meta($target, $field)['sha'] !== $job['target_sha']) {
throw new RuntimeException("Content changed during apply: $target");
}
update_field($field['key'], wp_slash($html), $target);
$saved = acf_bulk_meta($target, $field);
if ($saved['html'] !== $html) {
throw new RuntimeException("Stored value differs from approved HTML: $target");
}
acf_bulk_emit($event + ['status' => 'written', 'target_sha' => $saved['sha']]);
}
} catch (Throwable $e) {
WP_CLI::error($e->getMessage());
}
PHP
)
set -o noclobber
ACF_BULK_MODE="$mode" wp --url="$WP_SITE_URL" --user="$WP_RUN_USER" \
eval "$php" < "$2" > "$3"
Without a raw metadata read, an export can capture rendered shortcodes or generated paragraphs and store them back as if they were editor content. The write uses the field key so ACF can establish the hidden field reference on a new target; wp_slash() compensates for WordPress’s unslashing in its metadata write path. A read-back mismatch may mean a save hook changed the content after the write, so inspect the live row rather than assuming the failure left it untouched.
Review the translation and run a write-free plan
Run from the WordPress installation directory, or from a directory with WP-CLI configured for that installation. Set WP_SITE_URL to the exact site URL and WP_RUN_USER to the ID or login of a WordPress user allowed to edit both posts. Keep the working files outside public web directories.
export WP_SITE_URL='https://example.invalid'
export WP_RUN_USER='localization-editor'
bash acf-bulk.sh export acf-map.json acf-export.json
cp -n acf-export.json acf-approved.json
# Edit approved_html in each row of acf-approved.json.
bash acf-bulk.sh plan acf-approved.json acf-plan.jsonl
Replace the example site and user before running the commands. Keep acf-export.json unchanged; it records the original target HTML alongside the source. A successful plan reports would_write or unchanged for every row, but doesn’t establish that the translated HTML is structurally or editorially correct.
Use HTML Translate to compare a representative translated fragment against its source before approving the batch.
- Compare headings, links, tables, placeholders, and shortcodes against
source_html. If the destination already contains locale-specific links or notices, compare againsttarget_htmltoo. - Check JSON escaping with a JSON-aware editor. An HTML attribute quote appears as
\"inside the JSON string; that backslash is not part of the decoded HTML. - Treat a
wp_kses_post()mismatch as a review stop. It can flag legitimate markup, such as an embed, as well as unwanted HTML; handle exceptions through an explicitly reviewed workflow instead of turning the check off or silently stripping tags.
Never treat a clean HTML filter result as translation approval. An allowed tag can still contain the wrong link, and a perfectly valid paragraph can still omit a legal qualification.
Apply a small batch and verify the rendered field
Back up the database, test on staging, then send a small production batch first. Pause editor saves and relevant sync jobs for the affected posts during the write window. The hashes detect many intervening changes, but the last comparison and the metadata write are separate operations, not an atomic lock.
bash acf-bulk.sh apply acf-approved.json acf-apply.jsonl
wp --url="$WP_SITE_URL" --user="$WP_RUN_USER" \
post meta get 782 product_details --format=json
Replace 782 and product_details with the target ID and actual field name. A writing event without written means you need to inspect that row: the command may have stopped before the update or after a save hook modified it. The report isn’t a transaction or a rollback file, and the script refuses to overwrite any existing output path.
Open the localized page and the ACF editor, check the main links and shortcodes, then test a normal editor save. If metadata is correct but the page is stale, purge the relevant page or fragment cache and retest. If a batch stops partway through, compare the report and live values against the backup, then export the outstanding rows again before deciding what to retry.
Common mistakes and troubleshooting
- The translation lands on the wrong locale. The script verifies post eligibility, not translation relationships. Recheck
source_id,target_id, andWP_SITE_URLagainst the plugin’s mapping. - The import reports a stale export. Either stored value or its ACF reference changed. Re-export and reconcile the editor’s changes; don’t paste in new
source_shaortarget_shavalues just to pass the check. - The translated field reverts after saving the source. A translation plugin or hook may be synchronizing it. Inspect the field’s copy settings and check
acf/update_valuecallbacks before rerunning. - A field key is rejected as nested. A repeater or flexible content layout needs row- or layout-aware updates; a child
field_keyalone does not identify the stored row. - The editor shows correct copy, but the front end does not. Check whether the template reads
get_field()against the localized post ID or renders cached HTML from the source. - The plan reports filtered HTML for an ordinary field. Compare the exact
wp_kses_post()output to the approved fragment. Fix malformed or disallowed markup explicitly and run the plan again.
HTML File Translation Questions
Can you export with get_field() instead?
For a known, registered field, get_field($key, $post_id, false) disables ACF’s value formatting. The script reads metadata directly so it can inspect the stored value and reference separately and distinguish a missing value from an existing empty one.
Why write through update_field() instead of direct SQL?
update_field() uses ACF’s save path and maintains the field reference. Direct SQL bypasses that behavior and can leave cached metadata inconsistent with the database.
Can the script translate fields with different keys on each locale?
Not as written. It assumes both locales use the same field definition. A separate source and destination definition requires an explicit two-key map and validation of both field types, references, and editor locations.
Can a translation intentionally be empty?
Not through this batch. The script rejects blank approved_html to keep an omitted translation from clearing the target. Handle intentional removals as separately approved edits.
Does a successful plan guarantee that apply will succeed?
No. plan checks the current state without writing. Another editor can save afterward, and a hook can change the value during apply. Inspect the apply report and verify the stored and rendered content.
Can you use the same map for ACF options pages?
No. Options pages don’t use the numeric post IDs this script expects. Resolve the correct locale-specific options storage context and test it separately before attempting any bulk updates.