Check If A Twitch Channel Is Live Using PHP In WordPress

We recently did a little custom setup for our client, Mana Bar, who's site is running on WordPress. Whenever their Twitch channel is live, we wanted to show a slide on the main page of their site letting visitors know. We had a little issue with the slide not loading because of a caching plugin, but that's another story... for another day... So! There are two main steps here. One is getting your Client ID from Twitch and the second is throwing a bit of code into the functions.php file on your WordPress site. From there you can reference the custom function wherever you like.

Getting Your Twitch Client ID

  1. Sign into: https://dev.twitch.tv/
  2. Once you sign in, go to https://dev.twitch.tv/dashboard/apps
  3. Click on 'Register Your Application'
  4. Fill in the Name as Twitch Streamer Status For Website or something similar
  5. Fill in OAuth Redirect URI as your base website URL
  6. Choose Website Integration as the Application Category

Register your "app" using this information and it will give you your Client ID.




Setting Up The Function

Now that you have your Client ID you can setup the function for your WordPress site. Open up your functions.php file and enter the following code substituting your Client ID and channel name for the specified text.

function twitch_stream_live() {

    $channel = 'YOUR_TWITCH_USERNAME_HERE';
    $client_id = 'YOUR_TWITCH_CLIENT_ID_HERE';

    $url = 'https://api.twitch.tv/kraken/streams/' . $channel . '?client_id=' . $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;

}

Now with that in place, all you have to do is call your function wherever you want to use it. The function will return true if the stream is live or false if it isn't.

if( twitch_stream_live() ){

    // Do actions when streaming

} else {

    // Do actions when not streaming

}

What this means for you? You can now have a banner, photo, text, or links to your channel all show up anywhere on your site letting your own visitors know that you are currently live and they should tune in! Checking every single time the page is loaded could be a bit much, but that's where you can get a bit more creative. Store the information in a database or refresh and check again after certain time frames. That's all up to you! If you do something like that, feel free to share it below in the comments and help your fellow streamers out!

Hope this saves at least one of you out there a headache or two!

Posted on: November 26, 2017

No Comments Yet.

Leave a comment