This blog post, “Turn WordPress Posts into “Voice Blogs” with Python + OpenAI TTS” will show you how to pull posts from a WordPress site via the REST API, converts the article content to speech using OpenAI’s Text-to-Speech (TTS), saves an MP3, and (optionally) uploads the file back to your WordPress Media Library.

Below is a guided tour of how it works, with key snippets and tips to adapt it for your site.

What the script does (end-to-end)

  1. Loads config from environment (.env) and command-line flags.
  2. Lists recent WordPress posts (title, date, link).
  3. Lets you choose a post interactively.
  4. Fetches and sanitizes the post’s HTML into readable text.
  5. Streams TTS audio with OpenAI and writes an MP3.
  6. Optionally uploads the MP3 to WordPress using Application Passwords.

Prerequisites

  • Python 3.10+
  • Packages: requests, python-dotenv, openai
  • OpenAI API key in your environment (OPENAI_API_KEY)
  • WordPress site with REST API enabled (default for modern WP)
  • (Optional) WordPress Application Password for media upload

.env example:

Fetch posts via the WordPress REST API

The script relies on WordPress’s built-in REST endpoints:

List blog posts

It then prints a numbered list so you can pick the post:

Once selected, it fetches the full content:

Strip HTML into clean narration text

Blog HTML can be messy for TTS. The strip_html helper removes scripts/styles and, by default, removes code blocks (they’re often awkward to read aloud). You can include code with --include-code.

There’s also a length guard (TTS_MAX_CHARS) to avoid sending overly long inputs to TTS.

Stream speech to MP3 with OpenAI

The TTS step uses the OpenAI Python SDK’s streaming interface, which writes audio directly to disk (efficient and robust):

Why streaming? It avoids buffering the entire audio in memory and handles longer posts gracefully.

Optional: Upload MP3 back to WordPress

If you pass --upload (or answer “y” at the prompt), the script posts the MP3 to /wp-json/wp/v2/media using Basic Auth with a WordPress Application Password:

On success, WordPress returns the media id and source_url so you can embed or share the audio easily.

Command-line usage

The script is fully configurable via flags or environment variables:

Other useful flags

  • --include-code — read code blocks aloud.
  • --wp-user / --wp-app-pass — override .env values for uploads.

Security & reliability notes

  • Secrets: Keep your OPENAI_API_KEY and WP Application Password out of source control. Use .env locally and secure secrets in CI/CD.
  • Timeouts: Requests use sensible timeouts; you can tune them if your site is slow.
  • Rate limits: If you plan to batch through many posts, add brief sleeps and handle HTTP 429 gracefully.
  • Attribution: Consider adding an audio disclaimer (“This post was auto-narrated”) for transparency.

Discover more from CPI Consulting

Subscribe to get the latest posts sent to your email.