"Listen to This Article" Button
Adds a play button above posts that reads the article aloud with the visitor's browser text-to-speech, with no external service or cost.
Opens WPIDE on
Code
add_filter( 'the_content', function ( $content ) {
if ( ! is_singular( 'post' ) || ! in_the_loop() || ! is_main_query() ) {
return $content;
}
$button = '<p><button type="button" class="wpide-listen" hidden style="padding:6px 14px;border:1px solid currentColor;border-radius:20px;background:transparent;cursor:pointer;">▶ Listen to this article</button></p>';
$script = "<script>(function(){var b=document.querySelector('.wpide-listen');if(!b||!('speechSynthesis' in window)){return;}b.hidden=false;var playing=false;b.addEventListener('click',function(){if(playing){speechSynthesis.cancel();playing=false;b.innerHTML='▶ Listen to this article';return;}var c=b.closest('.entry-content,.wp-block-post-content')||document.querySelector('article');var u=new SpeechSynthesisUtterance((c?c.innerText:'').replace(b.innerText,''));u.lang=document.documentElement.lang||'en';u.onend=function(){playing=false;b.innerHTML='▶ Listen to this article';};speechSynthesis.cancel();speechSynthesis.speak(u);playing=true;b.innerHTML='■ Stop';});})();</script>";
return $button . $content . $script;
}, 25 );
Notes
Uses the browser's built-in speech voices, which vary by device. The button is hidden in browsers without speech support.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.