Find out in this tutorial how to display the number of subscribers to your WordPress YouTube channel using a shortcode.
The other day a subscriber asked me:
I would like to show on my website how many followers I have on my YouTube channel… is that possible?
Greetings
The answer is yes.
YouTube has an open API so you can take the values exposed in it and display them at will on your website.
Interesting, isn’t it?
Well, that’s exactly what you’re going to see in this tutorial:
How to take the subscriber data of a YouTube channel using the API and display it anywhere on your website thanks to a shortcode.
And here are the steps to follow:
Instructions for displaying the number of subscribers to your YouTube channel in WordPress
1. Get your YouTube API key and channel ID
To access your channel’s data using the YouTube API you need two things:
Once you have them, leave them at hand because you’ll be using them soon.
2. Create the shortcode
Add the following code at the end of functions.php or in your functionality plugin:
To see this and another 1097 code snippets of this website, login or subscribe here.
In this snippet you use the wp_remote_get
function to access the YouTube API data.
In this case, you have to access a URL with this structure:
https://www.googleapis.com/youtube/v3/channels?part=statistics&id=tu_channel_ID&key=tu_API_Key
That’s why you save the channel ID and YouTube API key data in variables and then concatenate them into the URL.
To display the data of your YouTube channel, replace the value of the following variables with the values you obtained in step 1:
- $channel_id = “your_channel_ID”
- $api_key = “your_API_Key”
By encapsulating the code in a shortcode, this allows you to display the result anywhere on the web.
If you use a browser that formats JSON (like Firefox) when you visit your channel’s URL you will see something like this:
You can display any of this data on your shortcode if you wish.
3. Enter the shortcode wherever you want
The advantage of the shortcodes is that you can insert them anywhere on the web.
You only have to write “[your_shortcode]”, in this case [youtube_subs], where you want it to be displayed (at the end of an article, in the sidebar, in the footer…)
Important:
- If you are using the classic editor, use the HTML tab to introduce the shortcode.
- In case you are already using the block editor you can add it to the normal paragraph block, the HTML block or the shortcode block. All of them will render the content correctly.
Conclusions
Now you know how to take values from the YouTube API and display the number of subscribers to your channel anywhere on the web thanks to a shortcode.
All you have to do now is implement it. 😉
Any questions? Let me know in the comments.
And if you want to give me any suggestion for future tutorials, leave it in the contact form. Advantages of being a subscriber. 😉