Why Voice AI Matters for WordPress Sites
If you’ve been building WordPress sites for a while, you already know the power of content in text form. But what if you could instantly convert any post, page, or custom post type into a polished, human‑like voice? That’s where text‑to‑speech (TTS) engines and voice‑cloning services come in. They let you add audio narration, dynamic podcasts, or accessibility features without hiring voice actors or writing scripts manually.
The TTS landscape is crowded, but one tool has been gaining traction among developers for its high‑quality, natural‑sounding voices and straightforward API: ElevenLabs. In this post we’ll walk through how to hook ElevenLabs into a WordPress site—whether you’re a plugin author, a theme developer, or just a blogger looking to add audio to your posts.
TL;DR
- Grab an ElevenLabs API key (affiliate link below).
- Install a lightweight “Voice‑AI” plugin or add a small snippet to your theme’s
functions.php.- Use the ElevenLabs API to synthesize speech from post content.
- Cache the resulting audio file for fast delivery.
Let’s dive in.
1. Set Up an ElevenLabs Account
- Click the affiliate link: https://try.elevenlabs.io/kr07zfuqn1bp (You’ll get a free tier with a generous monthly quota and a discount on paid plans.)
- Create an account and navigate to API Keys.
- Copy the key; you’ll need it for every request.
Tip: Keep the key in the WordPress Customizer or a
.envfile if you’re using the WP-CLI. Avoid hard‑coding it infunctions.php.
2. Decide How You Want to Trigger TTS
There are three common patterns:
| Pattern | When to Use | Example Trigger |
|---|---|---|
| Shortcode | Quick, per‑post control | [elevenlabs_audio] |
| Automatic | Every post auto‑generates audio | Hook into save_post
|
| Button | User‑initiated on the front‑end | “Listen to this article” button |
For this tutorial, we’ll implement a shortcode that users can place anywhere in a post. It keeps the setup minimal and lets authors decide where audio appears.
3. Write the Shortcode Handler
Add the following snippet to your theme’s functions.php or a site‑wide plugin:
/**
* Shortcode: [elevenlabs_audio]
* Generates a TTS audio file for the current post content.
*/
function elevenlabs_audio_shortcode( $atts ) {
// Get the global post content
global $post;
if ( empty( $post ) ) {
return '';
}
// Sanitize content: strip tags, collapse whitespace
$text = wp_strip_all_tags( $post->post_content );
$text = preg_replace( '/\s+/', ' ', $text );
// Build cache key
$cache_key = 'elevenlabs_audio_' . md5( $text . $post->post_modified_gmt );
// Check if we already have a cached URL
$audio_url = get_transient( $cache_key );
if ( $audio_url ) {
return sprintf(
'<audio controls preload="none"><source src="%s" type="audio/mpeg">Your browser does not support the audio element.</audio>',
esc_url( $audio_url )
);
}
// Prepare API request
$api_key = 'YOUR_ELEVENLABS_API_KEY'; // Replace with your key
$voice_id = 'EXAVITQu4vr4xnSDxMaL'; // Default voice; see docs
$payload = [
'text' => $text,
'voice' => [ 'voice_id' => $voice_id ],
'model' => 'eleven_multilingual_v1',
];
$response = wp_remote_post( 'https://api.elevenlabs.io/v1/text-to-speech/' . $voice_id, [
'headers' => [
'xi-api-key' => $api_key,
'Content-Type' => 'application/json',
],
'body' => wp_json_encode( $payload ),
'timeout' => 60,
] );
if ( is_wp_error( $response ) ) {
return ''; // Fail silently
}
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body, true );
if ( empty( $data['audio_url'] ) ) {
return ''; // No audio generated
}
// Cache for 24 hours
set_transient( $cache_key, $data['audio_url'], DAY_IN_SECONDS );
return sprintf(
'<audio controls preload="none"><source src="%s" type="audio/mpeg">Your browser does not support the audio element.</audio>',
esc_url( $data['audio_url'] )
);
}
add_shortcode( 'elevenlabs_audio', 'elevenlabs_audio_shortcode' );
What’s happening?
- Content sanitization – We strip HTML and collapse whitespace so the TTS engine gets clean text.
-
Caching – We use
set_transient()to store the generated audio URL for 24 h, preventing repeated API calls on every page load. -
API call – We hit ElevenLabs’
/text-to-speech/{voice_id}endpoint with a JSON payload. -
HTML5
<audio>– The shortcode outputs a simple, mobile‑friendly audio player.
Replace 'YOUR_ELEVENLABS_API_KEY' with the key you copied earlier. If you’re using a plugin or theme that already stores the key securely, adjust the retrieval accordingly.
4. Add the Shortcode to a Post
# How to Build a Voice‑Enabled WordPress Blog
...
[elevenlabs_audio]
When the page renders, the shortcode will trigger the API request (if not cached), and the browser will load the MP3 from ElevenLabs’ CDN.
5. Advanced: Voice Cloning
ElevenLabs offers a “voice cloning” feature that lets you create a custom voice from a short audio sample. This is great if you want a consistent brand voice across all posts.
Quick steps:
- Upload a 30‑second sample of your voice (or a brand mascot) to the ElevenLabs dashboard.
- Let the system process it; you’ll receive a voice ID.
- Replace the
$voice_idvariable in the snippet above with your custom ID.
$voice_id = 'YOUR_CUSTOM_VOICE_ID';
You can also expose this as a theme option so site owners can choose between default and custom voices without editing code.
6. Using JavaScript for On‑Demand Generation
If you prefer to generate audio client‑side (e.g., when a user clicks a button), here’s a curl‑style JavaScript example that fetches the audio and streams it:
async function generateAudio(text, voiceId = 'EXAVITQu4vr4xnSDxMaL') {
const apiKey = 'YOUR_ELEVENLABS_API_KEY';
const response = await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${voiceId}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'xi-api-key': apiKey,
},
body: JSON.stringify({
text,
voice: { voice_id: voiceId },
model: 'eleven_multilingual_v1',
}),
});
if (!response.ok) throw new Error('Failed to synthesize audio');
const data = await response.json();
return data.audio_url; // URL to the MP3
}
// Usage:
document.getElementById('listenBtn').addEventListener('click', async () => {
const audioUrl = await generateAudio(document.body.innerText);
const audio = new Audio(audioUrl);
audio.play();
});
Add a button with ID listenBtn to your page, and you’ll have a “Listen” feature that works entirely on the client.
7. Performance and SEO Considerations
-
Lazy‑load the
<audio>element withpreload="none"to avoid unnecessary bandwidth. - Serve from a CDN – ElevenLabs already hosts the MP3 on a fast CDN, but you can proxy through Cloudflare or AWS CloudFront if you need extra caching.
-
Add
aria-labelfor screen readers:
<audio controls preload="none" aria-label="Audio version of this article">
-
Meta tags – Include
audio/mpegin your<link rel="alternate">tags if you want search engines to index the audio version.
8. Troubleshooting Common Issues
| Problem | Fix |
|---|---|
| No audio appears | Check the browser console for 4xx/5xx responses. Verify your API key. |
| Audio is garbled | Make sure the text isn’t too long. ElevenLabs imposes a 500‑character limit per request for free tier. Split content if needed. |
| Rate limits | Use caching or queue requests. ElevenLabs offers higher limits on paid plans. |
| Voice doesn’t sound natural | Try a different voice ID. Some voices are more expressive than others. |
9. Next Steps: Building a Full‑Featured Plugin
If you’re comfortable, turn the snippet into a reusable plugin:
- Create a folder
elevenlabs-ttsinwp-content/plugins. - Add
elevenlabs-tts.phpwith plugin headers and the shortcode code. - Add an options page to store the API key and default voice.
- Hook into
save_postfor auto‑generation.
This gives site owners a UI to manage TTS settings without touching code.
Call to Action
Ready to give your WordPress content a voice? Start by signing up with ElevenLabs through the affiliate link: https://try.elevenlabs.io/kr07zfuqn1bp. Get a free tier, test the API, and add the shortcode to one of your posts. If you like what you hear, upgrade to a paid plan to unlock higher quality voices and more requests.
Happy coding—and happy listening!
Top comments (0)