DEV Community

VoiceDeveloper
VoiceDeveloper

Posted on

How to Use ElevenLabs with WordPress

Voice AI Meets WordPress: How to Use ElevenLabs for Text‑to‑Speech and Voice Cloning

If you’ve been following the surge in AI‑generated content, you’ve probably heard about text‑to‑speech (TTS) and voice cloning. Imagine turning your WordPress blog posts, help‑center articles, or even product videos into high‑quality spoken audio—right on the same page, with a voice that matches your brand. That’s exactly what ElevenLabs offers: a cloud‑based TTS engine that delivers natural‑sounding speech and lets you clone voices from just a few seconds of audio.

Below, I’ll walk you through setting up ElevenLabs in a WordPress environment, from API registration to generating, storing, and serving audio on your site. Whether you’re a seasoned developer or a WordPress hobbyist, this guide gives you the code snippets and best‑practice tips you need to get your audio workflow up and running.


Why ElevenLabs?

ElevenLabs stands out because of its:

  • Real‑time, high‑fidelity synthesis – voices that feel human, with expressive intonation.
  • Voice‑cloning pipeline – upload a short clip and create a custom voice ID that you can reuse across all your content.
  • Simple REST API – no heavy SDKs, just JSON over HTTPS.
  • Scalable pricing – pay per character, with generous free credits for experimentation.

If you’re ready to add a new dimension to your WordPress content, start here: https://try.elevenlabs.io/kr07zfuqn1bp


1. Get Your API Key

  1. Sign up at the ElevenLabs portal using the affiliate link above.
  2. Once logged in, navigate to Settings → API Keys.
  3. Copy the key; you’ll need it for every request.

Tip: Store the key in WordPress as a site option or environment variable so it’s not hard‑coded in your theme files.


2. Create a Simple WordPress Plugin

Instead of sprinkling code across functions.php, let’s encapsulate everything in a tiny plugin called elevenlabs-tts. Create a folder in wp-content/plugins/elevenlabs-tts and add an elevenlabs-tts.php file.

<?php
/*
Plugin Name: ElevenLabs TTS
Description: Generate spoken audio from post content using ElevenLabs.
Version: 1.0
Author: Your Name
*/

defined('ABSPATH') or die();

define('ELEVENLABS_API_KEY', 'YOUR_API_KEY_HERE'); // Replace with your key

/**
 * Generate TTS audio for a given text.
 *
 * @param string $text The text to synthesize.
 * @return string|false URL of the generated audio file, or false on failure.
 */
function el_generate_tts_audio($text) {
    $api_url = 'https://api.elevenlabs.io/v1/text-to-speech/eleven_monolingual_v1';
    $body   = json_encode([
        'text' => $text,
        'voice_settings' => [
            'stability' => 0.75,
            'similarity_boost' => 0.85
        ]
    ]);

    $response = wp_remote_post($api_url, [
        'headers' => [
            'Accept'        => 'application/json',
            'Content-Type'  => 'application/json',
            'xi-api-key'    => ELEVENLABS_API_KEY,
        ],
        'body' => $body,
        'timeout' => 60,
    ]);

    if (is_wp_error($response)) {
        return false;
    }

    $data = wp_remote_retrieve_body($response);
    $audio_url = wp_upload_bits('tts-' . md5($text) . '.mp3', null, $data);

    if ($audio_url['error']) {
        return false;
    }

    return $audio_url['url'];
}

/**
 * Shortcode to embed TTS audio for the current post.
 *
 * Usage: [elevenlabs_tts]
 */
function el_shortcode_tts() {
    $content = get_the_content();
    $audio_url = el_generate_tts_audio($content);

    if (!$audio_url) {
        return '<p>Audio generation failed.</p>';
    }

    return '<audio controls src="' . esc_url($audio_url) . '">Your browser does not support the audio element.</audio>';
}
add_shortcode('elevenlabs_tts', 'el_shortcode_tts');
Enter fullscreen mode Exit fullscreen mode

Important: Replace YOUR_API_KEY_HERE with the key you copied earlier.

Security: Never expose your API key in client‑side code. All synthesis happens server‑side here.


3. Using the Shortcode

Open any post or page editor and insert:

[elevenlabs_tts]
Enter fullscreen mode Exit fullscreen mode

When the page renders, the shortcode calls el_generate_tts_audio(), sends the post content to ElevenLabs, stores the resulting MP3 in the uploads folder, and returns an <audio> tag. The first visit will generate the file; subsequent visits will reuse the cached MP3.


4. Client‑Side Generation with JavaScript (Optional)

If you prefer to generate audio on the fly in the browser (e.g., for user‑generated text), you can use the Fetch API. The same API key must be kept secret, so we’ll expose a small REST endpoint that your JavaScript can hit.

/**
 * Register REST route for TTS.
 */
add_action('rest_api_init', function () {
    register_rest_route('el/v1', '/synthesize', [
        'methods'  => 'POST',
        'callback' => 'el_rest_synthesize',
    ]);
});

/**
 * REST callback that forwards to ElevenLabs.
 */
function el_rest_synthesize(WP_REST_Request $request) {
    $text = $request->get_param('text');
    $audio_url = el_generate_tts_audio($text);

    if (!$audio_url) {
        return new WP_REST_Response(['error' => 'Failed to generate audio'], 500);
    }

    return new WP_REST_Response(['url' => $audio_url], 200);
}
Enter fullscreen mode Exit fullscreen mode

Then, in your theme or a custom JS file:

async function synthesize(text) {
    const res = await fetch('/wp-json/el/v1/synthesize', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text })
    });

    const data = await res.json();
    if (data.url) {
        const audio = new Audio(data.url);
        audio.play();
    } else {
        console.error('Synthesis error:', data.error);
    }
}
Enter fullscreen mode Exit fullscreen mode

Security Note: This endpoint is public. If you’re exposing it, consider adding nonce validation or limiting usage to logged‑in users.


5. Voice Cloning Workflow

ElevenLabs’ voice cloning is a game‑changer for branded audio. Here’s a quick rundown:

  1. Upload a Sample – Use the API endpoint /v1/voices to upload a short audio clip (10–30 seconds).
  2. Create a Voice ID – ElevenLabs returns a voice_id that you can reuse.
  3. Generate Audio with the Custom Voice – In your request body, set voice_id instead of the default voice.
function el_generate_tts_with_clone($text, $voice_id) {
    $api_url = 'https://api.elevenlabs.io/v1/text-to-speech/' . $voice_id;
    // Rest of the request is identical to el_generate_tts_audio()
}
Enter fullscreen mode Exit fullscreen mode

Tip: Store the voice_id in your site options or a dedicated table so you can reference it across all posts.


6. Performance & Cost Tips

Consideration Recommendation
Caching Store generated MP3s in the uploads folder; use the MD5 hash of the text to avoid duplicate synthesis.
Batch Requests If you’re generating many audios at once (e.g., a podcast series), use the /batch endpoint to reduce round‑trips.
Monitoring Keep an eye on your character count; ElevenLabs charges per 1,000 characters.
Fallback If the API fails, provide a plain‑text link or a “Retry” button.

7. Putting It All Together

  1. Install the elevenlabs-tts plugin.
  2. Replace the placeholder API key.
  3. Add [elevenlabs_tts] to any post or page.
  4. (Optional) Use the voice‑cloning flow to create a custom brand voice.

Once set up, your audience can listen to any article right on the page, improving accessibility and engagement.


Final Thoughts

Adding AI‑powered voice to your WordPress site doesn’t have to be a complex engineering project. ElevenLabs gives you a clean API, realistic voices, and a voice‑cloning feature that can make your content feel truly branded. By integrating it into a small plugin, you keep everything modular, testable, and maintainable.

Give it a try, experiment with different voices, and watch your content come alive. Ready to turn words into sound? Dive in with ElevenLabs today: https://try.elevenlabs.io/kr07zfuqn1bp

Top comments (0)