Okay, so now that you have your very own brand spanking new YouTube API key, let's get you setup within your WordPress website..... We will be creating the "Short Code" to call a function that will present the YouTube video's View Count.
A shortcode is a WordPress-specific code that lets you do nifty things with very little effort. Shortcodes can embed files or create objects that would normally require lots of complicated, ugly code in just one line.Shortcodes Rock!
THE FOLLOWING STEPS INCLUDE MODIFYING AN IMPORTANT WORDPRESS SYSTEM FILE.
BE SURE TO COPY THIS FILE AND CREATE A BACKUP AND KNOW HOW TO REPLACE THE FILE IF YOU NEED TO.
YES, THIS IS AN ADVANCED ADDITION/EDIT OF ONE OF YOUR THEME FILES THAT CONTROLS THE CUSTOMIZED FUNCTIONS OF YOUR THEME.
Connecting your WordPress Website with Your YouTube API
Step 1: Login and click Editor
Login to your website and Select Appearance and Click the Editor link.
Step 2: Edit the functions.php file
Locate and then click on the functions.php file
Step 3: Add the Special Code
Step 3a - Copy the following code to Notepad or your preferred text editor.
function youtube_view_count_shortcode($params){ $videoID = $params['id']; $json = file_get_contents("<a href="https://www.googleapis.com/youtube/v3/videos?part=statistics&id=">https://www.googleapis.com/youtube/v3/videos?part=...</a>" . $videoID . "&key=PUTYOURYOUTUBEAPIKEYHERE"); $jsonData = json_decode($json); $views = $jsonData->items[0]->statistics->viewCount; return number_format($views);}add_shortcode('youtube_view_count', 'youtube_view_count_shortcode');
Step 3b - Edit with Your YouTube API Key
Replace thePUTYOURYOUTUBEAPIKEYHERE after $key= with your API key. (from Step 11)
Congrats! You now have created a Short Code for all your YouTube videos to display View Counts.
Let's finish up and make it happen!