NB: Make sure you do a back up of your theme, files and database before attempting the tutorials

Class PHP - API You Tube + Données vidéo
Web Hosting Canada

Last modified : Jul 22 2023

Estimated reading time : 7 minutes, 2 seconds - 123 words

We have created a basic PHP class that will let you connect to YouTube’s API and display a video or a channel based on its ID and matching data.

Here are the video’s data available:

  • Title
  • Description
  • Thumbnail
  • Views
  • Likes
  • Dislikes
  • Comments
  • Date Published
  • Channel Title
  • Tags
  • Default Language

Class PHP - API You Tube

/////////////////////////// Requires and includes admin theme  /////////////////////////

class WPVYouTubeAPI {
    private $apiKey;

    public function __construct($apiKey)
    {
       $this->apiKey = $apiKey;
    }

    /**
     * Retrieves videos by channel ID.
     * @param string $channelId The ID of the channel.
     * @param int $maxResults The maximum number of videos to retrieve.
     * @return array An array containing the channel name and videos.
     */
    public function wpvgetVideosByChannel($channelId, $maxResults = 10) {
        $url = "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={$channelId}&maxResults={$maxResults}&key={$this->apiKey}";
        $response = $this->wpvsendRequest($url);
        $videos = array();
        foreach ($response['items'] as $item) {
            $videoId = $item['id']['videoId'];
            $video = $this->getVideoDetails($videoId);
            $videos[] = $video;
        }
        // Retrieve the channel name from the first item in the response
        $channelName = $response['items'][0]['snippet']['channelTitle'];
        return array(
            'channelName' => $channelName,
            'videos' => $videos
        );
    }
    
    /**
     * Retrieves video details by video ID.
     * @param string $videoId The ID of the video.
     * @return array An array containing the video details.
     */
    public function wpvgetVideoDetails($videoId)
    {
        $url = "https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics&id={$videoId}&key={$this->apiKey}";

        $response = $this->wpvsendRequest($url);

        $video = array(
            'title' => $response['items'][0]['snippet']['title'],
            'description' => $response['items'][0]['snippet']['description'],
            'thumbnail' => $response['items'][0]['snippet']['thumbnails']['default']['url'],
            'views' => $response['items'][0]['statistics']['viewCount'],
            'likes' => $response['items'][0]['statistics']['likeCount'],
            'dislikes' => $response['items'][0]['statistics']['dislikeCount'],
            'comments' => $response['items'][0]['statistics']['commentCount'],
            'publishedAt' => $response['items'][0]['snippet']['publishedAt'],
            'duration' => $response['items'][0]['contentDetails']['duration'],
            'channelTitle' => $response['items'][0]['snippet']['channelTitle'],
            'tags' => $response['items'][0]['snippet']['tags'],
            'categoryId' => $response['items'][0]['snippet']['categoryId'],
            'defaultLanguage' => $response['items'][0]['snippet']['defaultLanguage'],
            'liveBroadcastContent' => $response['items'][0]['snippet']['liveBroadcastContent'],
            'license' => $response['items'][0]['status']['license'],
            'embedHtml' => $response['items'][0]['player']['embedHtml'],
            'allowedRegions' => $response['items'][0]['contentDetails']['regionRestriction']['allowed'],
            'blockedRegions' => $response['items'][0]['contentDetails']['regionRestriction']['blocked'],
            // Add any other data you want to retrieve
        );

        return $video;
    }

    /**
     * Sends a request to the specified URL using cURL.
     * @param string $url The URL to send the request to.
     * @return array The JSON response as an associative array.
     * @throws Exception If cURL encounters an error.
     */
    private function wpvsendRequest($url)
    {
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_ENCODING => "",
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            throw new Exception("cURL Error #:" . $err);
        }
        return json_decode($response, true);
    }
    
    /**
     * Retrieves the comments of a video by its video ID.
     * @param string $videoId The ID of the video.
     * @return array An array containing the video comments.
     */
    public function wpvgetVideoComments($videoId) {
        $url = 'https://www.googleapis.com/youtube/v3/commentThreads?videoId=' . $videoId . '&part=snippet&maxResults=10&key=' . $this->apiKey;
        $response = $this->wpvsendRequest($url);
        
        $comments = array();
        
        if (isset($response['items'])) {
            foreach ($response['items'] as $item) {
                $comment = $item['snippet']['topLevelComment']['snippet']['textDisplay'];
                $comments[] = $comment;
            }
        }
        
        return $comments;
    }
    
    /**
     * Retrieves the channel ID from a video by its video ID.
     * @param string $videoId The ID of the video.
     * @return string|null The channel ID, or null if not found.
     */
    public function wpvgetChannelIdFromVideo($videoId){
        $url = "https://www.googleapis.com/youtube/v3/videos?part=snippet&id={$videoId}&key={$this->apiKey}";
        $response = $this->wpvsendRequest($url);
        if (!empty($response['items'])) {
            $channelId = $response['items'][0]['snippet']['channelId'];
            return $channelId;
        }
        return null;
    }
    
    /**
     * Formats the number of views to a human-readable format.
     * @param int $views The number of views.
     * @return string The formatted views.
     */
    public function wpvformatViews($views) {
        if ($views >= 1000000000) {
            return round($views / 1000000000, 1) . ' billion';
        } elseif ($views >= 1000000) {
            return round($views / 1000000, 1) . ' million';
        } elseif ($views >= 1000) {
            return round($views / 1000, 1) . ' thousand';
        } else {
            return $views;
        }
    }
   
}

We will now call the PHP class and display the data. You need to update your API key in the $apiKey variable and then make call dynamically your video’s ID in the $videoId variable.

// API Call Class PHP
$apiKey = 'YOUR API KEY HERE';
$youtube = new WPVYouTubeAPI($apiKey);
$videoId = 'YOUR VIDEO ID HERE';

// Get video details
$videoDetails = $youtube->wpvgetVideoDetails($videoId);
$channelId = $youtube->wpvgetChannelIdFromVideo($videoId);
$publishedDate = date('Y-m-d', strtotime($videoDetails['publishedAt']));

// Echo the title of the video
echo 'Titre : ' . $videoDetails['title'] . '<br>';

//echo 'Description : ' . $videoDetails['description'] . '<br>';
echo '<img src="' . $videoDetails['thumbnail'] . '" alt="Thumbnail de la vidéo"><br>';

// Display the formatted duration
//echo 'Durée : ' . $formattedDuration . '<br>';

// Echo the channel title
echo 'Channel : ' . $videoDetails['channelTitle'] . '<br>';

// Echo the published date of the video
echo 'Publié le : ' . $publishedDate . '<br>';

// Check if default language is available
if (!empty($videoDetails['defaultLanguage'])) {
    echo 'Language : ' . $videoDetails['defaultLanguage'] . '<br>';
} else {
    echo 'Language : Undefined<br>';
}

// Display license
if (!empty($videoDetails['license'])) {
    echo 'License : ' . $videoDetails['license'] . '<br>';
} else {
    echo 'License : Not specified<br>';
}

// Display the Channel Name of the video 
if (!empty($videoDetails['channelId'])) {
    $maxResults = 10; // Maximum number of videos to retrieve
    $videosData = $youtube->wpvgetVideosByChannel($channelId, $maxResults);
    $channelName = $videosData['channelName'];
    $videos = $videosData['videos'];
    echo "Channel Name: $channelName<br>";
} else {
    echo "No channel found for the video.<br>";
}

// Display the tags
if (isset($videoDetails['tags'])) {
    if (is_array($videoDetails['tags'])) {
        $formattedTags = array_map('ucfirst', $videoDetails['tags']); // Apply ucfirst to each tag
        $tags = implode(', ', $formattedTags);
        echo 'Tags: ' . $tags . '<br>';
    } else {
        $tags = ucfirst($videoDetails['tags']); // Capitalize the first letter
        echo 'Mots-clés : ' . $tags . '<br>';
    }
} else {
    echo 'Mots-clés : None<br>';
}

// Display the Views of the video 
echo 'Vues : ' . $youtube->wpvformatViews($videoDetails['views']) . '<br>';

// Display the Likes of the video 
echo 'Passioné(e)s : ' . $videoDetails['likes'] . '<br>';

// Display the Dislikes of the video 
$dislikes = $videoDetails['dislikes'];
if ($dislikes > 0) {
    echo 'Dislikes : ' . $dislikes . '<br>';
} else {
    echo 'Dislikes : 0<br>';
}

// Display the Favorites of the video 
$favorites = $videoDetails['favorites'];
if ($favorites > 0) {
    echo 'Favorites : ' . $favorites . '<br>';
} else {
    echo 'Favorites : 0<br>';
}

// Display the Comments of the video 
echo 'Comments : ' . $videoDetails['comments'] . '<br>';

You can also include Font Awesome Version 5 icons by creating an enqueue script or add it in the Class PHP WPVYouTubeAPI class.

// Enqueue Font Awesome 5 in WordPress 
function themespress_load_font_awesome() {
    // You can find the current URL for the latest version here: https://fontawesome.com/start
    wp_enqueue_style( 'font-awesome-free', '//use.fontawesome.com/releases/v5.6.3/css/all.css' );
}
add_action( 'wp_enqueue_scripts', 'themespress_load_font_awesome' );

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>