How to Bulk Translate WordPress HTML Exports Without Breaking Gutenberg Blocks

Use a post_content round trip: export Gutenberg’s stored block markup, translate approved text, and write the result to a separate file for each destination post. This works for HTML fragments taken from the Code editor, WP-CLI, or a WordPress XML export; the production caveat is that Gutenberg validates more than the visible HTML. An edit that looks fine in a browser can still trigger block recovery in the editor.

Start with paragraphs and headings, where the copy is easy to isolate. Route blocks that store copy in JSON, generate it dynamically, or reference shared content through a separate editor-based pass. That split gives you a batch you can automate without treating every string inside a block as a translation target.

Identify what your export actually contains

SourceWhat to look forHow to use it
Code editor or raw post export<!-- wp:paragraph --> around saved HTMLUse the stored content directly as the source for each post.
WordPress XML export (WXR)<content:encoded> inside each post’s <item>Use an XML parser to read the element’s text and associate it with wp:post_id. Don’t run a translator over the XML package.
Rendered page or static-site exportFront-end HTML such as <main>, often without block delimitersUse it for visual QA. Get the stored post content from WordPress before attempting a Gutenberg round trip.

Never strip <!-- wp:… --> comments as HTML cleanup. They mark block boundaries and can carry attributes that don’t appear in the visible markup.

Export one raw file per WordPress post

Run WP-CLI against the source installation. Start with a small, reviewed ID list; a production batch should also have a mapping from source ID to target language and, when it exists, destination ID. Slugs are poor batch keys because they can change during localization.

set -eu
mkdir -p source

# Review ids.txt before running this loop: one numeric post ID per line.
wp post list --post_type=page --post_status=publish --field=ID > ids.txt

while IFS= read -r id; do
  POST_ID="$id" wp eval '
    $post = get_post((int) getenv("POST_ID"));
    if (!$post) {
        WP_CLI::error("Post not found.");
    }
    echo $post->post_content;
  ' > "source/$id.html.tmp"
  mv "source/$id.html.tmp" "source/$id.html"
done < ids.txt

Reading post_content directly bypasses front-end rendering and avoids adding a newline to the field. Check that each selected ID yielded the expected file and that a known block post still contains its opening and closing comments. A WXR extraction should produce the same kind of fragment, not a file with a <content:encoded> wrapper.

Choose what can change before handing off copy

A heading is a useful boundary test: its text can change while its level, classes, and anchor stay put. Here’s an edit that translates the label but accidentally changes the heading level and breaks existing links to the anchor:

<!-- wp:heading {"level":3,"anchor":"shipping"} -->
<h2 class="wp-block-heading" id="livraison">Livraison</h2>
<!-- /wp:heading -->

The block declares level 3, but the saved tag is <h2>. Gutenberg can flag a mismatch when it regenerates the saved markup; links to #shipping also stop resolving.

<!-- wp:heading {"level":3,"anchor":"shipping"} -->
<h3 class="wp-block-heading" id="shipping">Livraison</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Livraison et retours</p>
<!-- /wp:paragraph -->

This edit preserves the heading’s saved structure and leaves the anchor available to existing links. Compare the localized excerpt with its source: only the rendered text should differ for this pass.

ContentExampleTranslation route
Plain visible text<p>Shipping &amp; returns</p>Replace the text node and HTML-escape the translated text on output.
Rich text with inline elements<strong>Free</strong> shippingTranslate the whole phrase with markup placeholders, or edit the block directly if the emphasis must move.
Accessibility textalt="Delivery van"Localize it in the block’s own controls where available. Preserve deliberately empty alt="" for decorative images.
Nested or serialized state<!-- wp:columns -->, {"level":3}Preserve it in a text-only batch. Use the owning block’s editor when a translatable field lives in its attributes.
Shared or dynamic content<!-- wp:block {"ref":42} /-->Translate the synced pattern or other source record separately, then link to the localized equivalent if needed.

Apply reviewed translations without reserializing HTML

Keep one JSON job per source file. Give each entry an exact source text span and enough unchanged context to identify it once. The source field uses the stored HTML spelling, including entities; target is ordinary translated text. This example is a job for source/123.html:

[
  {
    "left": "<h3 class=\"wp-block-heading\" id=\"shipping\">",
    "source": "Shipping",
    "right": "</h3>",
    "target": "Livraison"
  },
  {
    "left": "<p>",
    "source": "Shipping &amp; returns",
    "right": "</p>",
    "target": "Livraison et retours"
  }
]

A source file containing literal &amp; won’t match a manifest that spells it as a bare &. If the same paragraph appears twice, expand an anchor with adjacent unchanged markup instead of letting the program guess which occurrence to edit.

Use this batch only for reviewed HTML text spans. Never aim a text replacement at a tag, an attribute, a shortcode, or a block comment.

Save the applicator below as apply_translations.py. It checks every match against the original file, rejects overlapping edits, and writes the result to a new destination. It doesn’t parse Gutenberg blocks or decide which text is safe to translate.

# apply_translations.py
import argparse
import html
import json
from pathlib import Path

def apply(source: str, entries: list) -> str:
    if not isinstance(entries, list) or not entries:
        raise ValueError("Expected a nonempty list of translation entries")

    edits = []
    for index, entry in enumerate(entries, 1):
        keys = ("left", "source", "right", "target")
        if not isinstance(entry, dict) or any(
            not isinstance(entry.get(key), str) for key in keys
        ):
            raise ValueError(f"Entry {index}: expected four string fields")
        left, original, right, target = (entry[key] for key in keys)
        if not left or not original or not right or "<" in original:
            raise ValueError(f"Entry {index}: use a nonempty, anchored text span")
        needle = left + original + right
        position = source.find(needle)
        if position == -1 or source.find(needle, position + 1) != -1:
            raise ValueError(f"Entry {index}: source span must match exactly once")
        start = position + len(left)
        edits.append((start, start + len(original), html.escape(target, quote=False)))

    parts = []
    cursor = 0
    for start, end, replacement in sorted(edits):
        if start < cursor:
            raise ValueError("Translation spans overlap")
        parts.extend((source[cursor:start], replacement))
        cursor = end
    parts.append(source[cursor:])
    return "".join(parts)

def main() -> None:
    parser = argparse.ArgumentParser(description="Apply reviewed text translations")
    parser.add_argument("source", type=Path)
    parser.add_argument("destination", type=Path)
    parser.add_argument("--strings", required=True, type=Path)
    args = parser.parse_args()
    try:
        source = args.source.read_bytes().decode("utf-8")
        entries = json.loads(args.strings.read_text(encoding="utf-8"))
        result = apply(source, entries).encode("utf-8")
        with args.destination.open("xb") as output:
            output.write(result)
    except (OSError, ValueError) as exc:
        parser.exit(1, f"{parser.prog}: {exc}\n")

if __name__ == "__main__":
    main()

Matching against the original avoids a translated string becoming input to a later replacement. The program escapes each target for a text node, so a translated ampersand becomes &amp; in the saved HTML rather than being interpreted as part of an entity. Exclusive creation mode also prevents accidental overwrites, including attempts to write back to the source path.

set -eu
mkdir -p translated
for job in jobs/*.json; do
  [ -f "$job" ] || continue
  id=${job##*/}
  id=${id%.json}
  python3 apply_translations.py "source/$id.html" "translated/$id.html" --strings "$job"
  diff -u "source/$id.html" "translated/$id.html" || [ "$?" -eq 1 ]
done

Save the sample manifest as jobs/123.json and use a fresh output directory for each revision. Review the diffs for edits outside the intended copy. A match error usually means the source changed after handoff or the anchor is ambiguous; don’t turn it into an unrestricted replacement.

Validate the block tree and open a staging draft

Use WordPress’s parser to compare block names, nesting, and comment attributes before creating a draft. For this text-only route, any difference in those fields is a reason to stop.

SOURCE=source/123.html TARGET=translated/123.html wp eval '
  $shape = static function ($blocks) use (&$shape) {
      return array_map(static function ($block) use (&$shape) {
          return [
              $block["blockName"],
              $block["attrs"],
              $shape($block["innerBlocks"]),
          ];
      }, $blocks);
  };
  $source = file_get_contents(getenv("SOURCE"));
  $target = file_get_contents(getenv("TARGET"));
  if ($source === false || $target === false ||
      $shape(parse_blocks($source)) !== $shape(parse_blocks($target))) {
      WP_CLI::error("Unable to read files or block structure differs.");
  }
  WP_CLI::success("Block structure matches.");
' && wp post create translated/123.html \
  --post_type=page --post_status=draft \
  --post_title='Livraison et retours' --porcelain

parse_blocks() reads the serialized block tree; it doesn’t check whether a static block’s registered save function agrees with the saved HTML. On staging, use the same block plugins and versions as production, then open the returned draft ID in the visual editor and check for invalid blocks before accepting recovery or saving. Preview the draft as well: check longer labels, links, and dynamic blocks, which may depend on metadata not carried in post_content.

Use HTML Translate to compare localized HTML excerpts visually, then confirm block validity in the WordPress editor.

Before publishing, associate the draft with the source post in the multilingual plugin, set its target language, and review localized internal links, the slug, and any SEO fields. Creating a draft with WP-CLI doesn’t establish those relationships on its own.

Common mistakes and troubleshooting

  • The editor shows a Classic block instead of the original blocks. Check whether the file came from a rendered page or whether a minifier removed <!-- wp:… --> comments. Re-export post_content.
  • The tree matches but the editor reports invalid content. Check the saved tags and classes against the source and confirm the block plugin version matches production. Inspect the changed block in the Code editor before using recovery.
  • Translated text displays literal entity syntax. A target containing &amp; was likely escaped again. Put a plain ampersand in the JSON target.
  • A pattern still shows the source language. The page still references the original ref. Translate the shared record and update the reference through WordPress rather than editing all its instances independently.
  • Links reach the right page but land at the top. The destination anchor no longer matches the link fragment. Keep the saved id stable or update and test all affected links together.
  • The staging draft looks different from the source page. Check the destination template, featured image, custom fields, and post type. These are not restored by copying post_content.

HTML File Translation Questions

Can you translate a WXR file directly?

Extract each post’s content:encoded text first. If the localized content must go back into WXR, write it through an XML serializer and test the import on staging rather than pasting raw HTML into XML.

Do block comments ever contain translatable copy?

Yes. Some blocks store user-facing labels or other copy in comment JSON. Change those fields through the registered block’s controls or a block-aware implementation, not through the text-span batch.

Yes, and many translations need that freedom. Edit the whole sentence as rich text and move the <a> or <strong> span with the words it applies to; don’t translate each text node in isolation.

What should happen when the source changes after handoff?

Export the latest post_content, reconcile the affected translation entries, and rebuild to a new destination directory. An exact-match failure helps catch stale copy before it reaches the site.

Does a successful visual preview mean the file is safe to import?

No. A browser can render HTML even when Gutenberg considers its serialization invalid. Check the stored draft in the visual editor and confirm that any dynamic or shared blocks resolve against the destination site’s data.

Translate a file →