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.

Start Coding

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: https://api.twitch.tv/kraken/streams/{stream_name}/?client_id={your_client_id}.

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:

function is_streamer_live( $channel, $client_id ) {
// Get current status
$url = 'https://api.twitch.tv/kraken/streams/' . esc_html( trim( $channel, '/' ) ) . '?client_id=' . esc_html( $client_id );
$response = wp_remote_get( $url );
if ( ! is_wp_error( $response ) && $response['response']['code'] === 200 ) {
$body = json_decode( wp_remote_retrieve_body( $response ) );
if ( empty( $body->stream ) ) {
return false;
} else {
return true;
}
}
return false;
}

view raw
functions.php
hosted with ❤ by GitHub

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 200.

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.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply