I worked on a site for a friend some time ago and she is a streamer on Twitch. What I wanted to add is a widget in the header that shows her Twitch stream status, so when she is live, if someone goes to the site, they can see that, and eventually check her live Twitch stream.
Knowing if someone is live via the API that Twitch provides is very easy. Let’s check how I did that.
Create an App on Twitch
First of all, from a few months, Twitch requires an app to use any of their API endpoints. Before this switch, you were able to use the endpoint that we are going to use without using an app, but now it’s mandatory to have it.
Go to this page and, at the bottom, create a new app for your site and copy its client ID.
Once you created the app and you have the client ID, you are ready to start coding.
The endpoint that we are going to use is:
And this is the snippet used to get a boolean value indicating the stream status,
true if it’s live,
false if it’s not:
The code is very basic and easy to understand.
At first we create the complete URL, including the channel name and the your app’s client ID.
Then we get the response from the API with
wp_remote_get. The API will return an empty body if the streamer is offline, so we just make sure that there are no errors in fetching data from the endpoint and that the response code is
In that case, we check if the response is empty, in which case we return
false because the streamer is offline. Otherwise, we just return
true ignoring all the data included in the response.
You could also expand the code and return more data, like the streamer name, images from the stream, etc. It’s up to you!
Let’s Build a Plugin
On the 21st January 2017 I streamed live on Twitch the development of a WordPress plugin based on this code! You can see the recording of the stream here or on my YouTube channel.