// 1. Add the Read Aloud button and inject content safely
function add_read_aloud_feature($content) {
if (is_single() && in_the_loop() && is_main_query()) {
// Prepare clean text
$clean_text = wp_strip_all_tags(get_the_content());
// Inject data to JS via a global variable
wp_add_inline_script('read-aloud-script', 'const postContent = ' . json_encode($clean_text) . ';', 'before');
$button = '
<div class="read-aloud-wrapper" style="margin-bottom: 20px;">
<button type="button" class="read-aloud-btn" onclick="readAloud(this)" aria-label="Listen to this article" style="padding: 10px 20px; cursor: pointer; background: #0073aa; color: white; border: none; border-radius: 5px;">
🔊 Read Post Aloud
</button>
</div>';
return $button . $content;
}
return $content;
}
add_filter('the_content', 'add_read_aloud_feature');
// 2. Register and add the JavaScript
function enqueue_read_aloud_script() {
if (is_single()) {
// Enqueue a dummy handle to attach our inline script to
wp_register_script('read-aloud-script', '', [], '', true);
wp_enqueue_script('read-aloud-script');
wp_add_inline_script('read-aloud-script', '
function readAloud(button) {
if (window.speechSynthesis.speaking) {
window.speechSynthesis.cancel();
button.innerText = "🔊 Read Post Aloud";
return;
}
const utterance = new SpeechSynthesisUtterance(postContent);
// Adjust rate and pitch to sound more human
utterance.rate = 0.95;
utterance.pitch = 1.0;
const voices = window.speechSynthesis.getVoices();
const naturalVoice = voices.find(voice =>
voice.lang.includes("en") && (voice.name.includes("Natural") || voice.name.includes("Google") || voice.name.includes("Enhanced"))
) || voices.find(voice => voice.lang.includes("en"));
if (naturalVoice) {
utterance.voice = naturalVoice;
}
button.innerText = "âšī¸ Stop Reading";
utterance.onend = () => {
button.innerText = "🔊 Read Post Aloud";
};
utterance.onerror = () => {
button.innerText = "🔊 Read Post Aloud";
};
window.speechSynthesis.speak(utterance);
}');
}
}
add_action('wp_enqueue_scripts', 'enqueue_read_aloud_script');