Programmatic WordPress Localization via REST API and Python (Full Workflow)
Use GET /wp/v2/posts to retrieve WordPress content and an authenticated POST to save the reviewed translation. The standard posts API can create or update the translated text, but its documented fields don’t assign a content language or link the translation to its source.
Keep three jobs separate: retrieving the source, preparing the translation, and saving it to WordPress. Start with a new draft so you can inspect the result before publication. If your site uses a multilingual plugin or custom API, verify its language and linking requirements separately; a successful post write doesn’t prove those jobs are done.
Separate Post Translation from WordPress Localization
Where each part of the localization workflow belongs
| Job | Relevant setting, file, or endpoint | What it does not establish |
|---|---|---|
| Localize theme or plugin interface strings | POT, PO, and MO files | Whether an individual post has translated content |
| Set the WordPress dashboard language | Site Language | Whether an individual post has a content language |
| Save translated post text | POST /wp/v2/posts with title and content | Whether the new post is linked to the original |
| Assign a content language or link two versions | Site-specific plugin or custom API documentation; no standard language argument in the documented post write routes | Whether the translated text and markup are correct |
The WordPress localization documentation covers interface strings. The posts endpoint reference covers post data. If your task is to translate the body of an article, use the latter to move content in and out of WordPress.
Discover the REST API and Authenticate over HTTPS
Start with the target site’s API index. There’s no single REST API root for all WordPress installations. Use that site’s index to locate its posts collection and send an OPTIONS request to inspect the endpoint’s capabilities before writing anything.
GET <site REST API index URL>
OPTIONS <site URL for the /wp/v2/posts collection>
These are HTTP request outlines, not shell commands. Use the full HTTPS URLs for your site; /wp/v2/posts identifies the route within the API, not a complete URL. Inspect the response from the same site that will receive your draft rather than assuming two installations expose the same capabilities.
Create an Application Password for the WordPress user that will make the requests. WordPress shows it only once, and you can revoke it individually. The write script below uses it with HTTP Basic Authentication over HTTPS.
Never send a WordPress Application Password over plain HTTP or store it in a translation file.
Retrieve the Source Post Before Preparing the Translation
GET /wp/v2/posts?slug=<source-post-slug>&status=publish
GET /wp/v2/posts?search=<source-title-text>&status=publish
GET /wp/v2/posts?status=publish&per_page=10&page=1
GET /wp/v2/posts?status=publish&per_page=10&page=2
Add these query strings to your site’s posts collection URL, encoding any query values that need it. Use slug when you know the source slug and search when you only have text to match. A request without pagination arguments defaults to page=1 and per_page=10, so the first response is not a complete export.
The default status is publish. If the source is an unpublished draft, request status=draft with authentication and confirm that the API user can retrieve it. Before handing the text off, record the source post ID and confirm the title and body match the intended revision; a search result alone isn’t a reliable source identifier.
Build a Draft Payload from the Reviewed Translation
Save the translated title and body together as a UTF-8 JSON file named translated-draft.json. Translate the reader-facing copy, not the HTML tag names or attribute names. Review the destination slug as an editorial choice rather than letting it change as a side effect of translating the title.
{
"slug": "politica-de-devoluciones",
"status": "draft",
"title": "Política de devoluciones",
"content": "<p>Puedes devolver los productos en un plazo de 30 días.</p>\n<p>Conserva el comprobante de compra.</p>"
}
The content field holds the post body, including markup, rather than a complete HTML document. The JSON escape \n separates the paragraphs in the string; the paragraph tags are what structure the HTML. Check the file as JSON before submitting it, especially if the body contains quotation marks inside HTML attributes.
Never infer a post’s language from
Site Languageor add a guessedlanguagefield to a standard post request.
Send the Payload and Save the Response with Python
The script takes a full post endpoint URL, a source JSON path, and a different destination JSON path. It sends one POST and writes the decoded WordPress response to a new file. The URL selects the operation: the collection creates a post, while the route ending in the translated post’s ID updates that post.
# wordpress-post.py
import argparse
import base64
import json
import os
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import urlsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def main():
parser = argparse.ArgumentParser(
description="Send a WordPress post payload and save the JSON response."
)
parser.add_argument("endpoint")
parser.add_argument("source", type=Path)
parser.add_argument("destination", type=Path)
args = parser.parse_args()
user = os.environ.get("WP_USERNAME")
password = os.environ.get("WP_APPLICATION_PASSWORD")
if not user or not password:
parser.error("Set WP_USERNAME and WP_APPLICATION_PASSWORD.")
try:
endpoint = urlsplit(args.endpoint)
if (
endpoint.scheme != "https"
or not endpoint.hostname
or endpoint.username is not None
or endpoint.password is not None
or endpoint.fragment
):
parser.error("Use a full HTTPS endpoint without credentials or a fragment.")
if args.source.resolve() == args.destination.resolve():
parser.error("Source and destination must be different files.")
if args.destination.exists():
parser.error("Choose a new destination file.")
if not args.destination.parent.is_dir():
parser.error("The destination directory must already exist.")
payload = json.loads(args.source.read_text(encoding="utf-8"))
if not isinstance(payload, dict):
parser.error("The source must contain a JSON object.")
if payload.keys() - {"slug", "status", "title", "content"}:
parser.error("Use only slug, status, title, and content in this script.")
if any(not isinstance(value, str) for value in payload.values()):
parser.error("All supplied post fields must be strings.")
if not {"title", "content"}.issubset(payload):
parser.error("Supply both title and content.")
credentials = f"{user}:{password}".encode("utf-8")
token = base64.b64encode(credentials).decode("ascii")
request = Request(
args.endpoint,
data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
headers={
"Authorization": f"Basic {token}",
"Content-Type": "application/json",
},
method="POST",
)
opener = build_opener(NoRedirect())
with opener.open(request, timeout=30) as response:
result = json.loads(response.read())
with args.destination.open("x", encoding="utf-8") as output:
json.dump(result, output, ensure_ascii=False, indent=2)
output.write("\n")
except HTTPError as exc:
parser.exit(1, f"WordPress request returned HTTP {exc.code}.\n")
except URLError as exc:
parser.exit(1, f"Could not complete the API request: {exc.reason}\n")
except (OSError, ValueError) as exc:
parser.exit(1, f"Could not complete the workflow: {exc}\n")
if __name__ == "__main__":
main()
The script refuses redirects so it won’t follow a redirected request with the Application Password; supply the final HTTPS endpoint. It encodes the request as UTF-8 and keeps accented text readable in the saved JSON. An output-file error can occur after a successful remote write, so check WordPress before retrying a create request when the outcome is uncertain.
Set WP_USERNAME and WP_APPLICATION_PASSWORD in the environment that runs Python. Replace the quoted placeholder with the collection URL discovered on your site.
python3 wordpress-post.py \
'<HTTPS URL for the /wp/v2/posts collection>' \
translated-draft.json \
created-post.json
Inspect created-post.json and record the returned post id. Check that the post is a draft and that its title and content match the intended translation. Keep this response separate from the original payload so you can tell what was requested and what WordPress returned.
Update the Translated Draft Without Creating a Duplicate
Once the translated draft exists, use POST /wp/v2/posts/<id> for revisions. Save the next payload as revised-translation.json. If only the copy has changed, send title and content rather than resending the slug or status.
{
"title": "Política de devoluciones",
"content": "<p>Puedes devolver los productos en un plazo de 30 días.</p>\n<p>Guarda el comprobante de compra.</p>"
}
The post ID belongs in the URL, not in this payload. Omitting slug and status keeps the request focused on the two fields you intend to change. Verify that the ID comes from the translated draft’s create response, not from the source post.
python3 wordpress-post.py \
'<HTTPS URL for /wp/v2/posts/<translated-post-id>>' \
revised-translation.json \
updated-post.json
Use the same environment variables for the update and a new destination file for the response. Compare the returned id with the one in created-post.json; they should identify the same post. If you use the collection URL instead, the request creates another post rather than editing the draft.
Validate the Draft and Its Language Relationship
- Open the draft identified by the response
id. Compare its title and body with the reviewedtitleandcontentin the payload. - Preview the rendered draft. Check that paragraph boundaries, links, and any markup in
contentsurvived the handoff and that the visible copy is in the intended language. - If the site requires a content language or links between versions, follow the installed plugin or custom API documentation and confirm the result there. A successful
POST /wp/v2/postsonly confirms the post write.
Use HTML Translate to compare the source and translated HTML before checking the rendered WordPress draft. If content is Gutenberg markup, check the original and the translation with the WordPress Gutenberg Markup Checker before opening the draft in the editor.
Common Mistakes and Troubleshooting
- The source post doesn’t appear. Check
slugandstatus. The defaultstatus=publishexcludes drafts; a draft lookup needs the appropriate status and authentication. - A batch stops after the first set of posts. The default is
per_page=10. Advancepageinstead of treating one collection response as the full set. - The write is rejected. Check
WP_USERNAME,WP_APPLICATION_PASSWORD, the API user’s access, and the exact HTTPS endpoint. If the endpoint redirects, use the final URL rather than disabling the script’s redirect guard. - Revisions create duplicate drafts. Use
POST /wp/v2/posts/<id>after the first create. If a create attempt didn’t save a response, look for the draft in WordPress before repeating the request. - The post is saved but doesn’t appear as a translation. A new
iddoesn’t establish a relationship. Verify the language and linking steps for the installed plugin or custom API. - JSON loads, but the draft renders incorrectly. Valid JSON only tells you that
contentis a readable string. Inspect the markup in that string and compare the rendered draft with the reviewed translation.
Programmatic WordPress Questions
Can the standard WordPress REST API translate a post?
The documented posts routes retrieve and save post data. Prepare the translation separately, then pass the translated title and content to the write endpoint.
Does changing Site Language set the language of a draft?
No. Site Language controls the WordPress dashboard language. Check your site’s multilingual setup for the separate content-language assignment.
Where does the source post ID go when creating a translation?
Keep it in your handoff records. The standard POST /wp/v2/posts create arguments don’t document a translation-link field; use the site-specific documentation for linking.
Which endpoint should an editor use for a second revision?
Use POST /wp/v2/posts/<id> with the translated post’s ID. The collection route is for creating a new post.
Are escaped accented characters a sign that JSON corrupted the translation?
No. Python’s json.dumps() defaults to ensure_ascii=True, which escapes non-ASCII characters without changing their decoded values. The script uses ensure_ascii=False to keep the saved text readable and encodes the request as UTF-8.
Related guides
- WordPress Multisite vs. Subdirectories for 10+ Languages: SEO & Performance Guide
- How to Translate HTML Files with Python (BeautifulSoup + DeepL or OpenAI API)
- Translate HTML Without Breaking Layout: Checklist + Safe Workflow
The script and sample files from this article are on GitHub: wordpress-post.