How to Display YouTube Feed

Posted on: February 6th, 2024
By: Tadeo Martinez

Here’s the code if you want to display a YouTube feed on your website in WordPress

function get_latest_videos_from_youtube_channel() {
    // Load the Google Client Library
    if (!class_exists('Google_Client')) {
		require_once get_template_directory() . '/google-api-php-client--PHP7.4/vendor/autoload.php';

    }

    // Set up the client
    $client = new Google_Client();
    $client->setDeveloperKey($GLOBALS['youtube']);
    $youtube = new Google_Service_YouTube($client);

    // Send a request to the API to get the latest 10 videos from a specific channel
    $searchResponse = $youtube->search->listSearch('id,snippet', array(
        'channelId' => 'channel_id',
        'type' => 'video',
        'order' => 'date',
        'maxResults' => 4,
    ));

    // Print the results
    ob_start();
	echo '<div class="row">';
    foreach ($searchResponse['items'] as $searchResult) {
		echo '<div class="col-lg-6" style="padding-top:15px;padding-bottom:15px;">';
        echo '<div class="video">';
        // echo '<h3>' . $searchResult['snippet']['title'] . '</h3>';
        // echo '<p>' . $searchResult['snippet']['description'] . '</p>';
        echo '<iframe width="100%" height="315" src="https://www.youtube.com/embed/' . $searchResult['id']['videoId'] . '" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
			echo '</div>';
			echo '</div>';
	}
	echo '</div>';
	wp_enqueue_script('iframe-js',get_theme_file_uri('/js/iframe.js'));
    return ob_get_clean();
}

add_shortcode('youtube_videos', 'get_latest_videos_from_youtube_channel');

Find your YouTube Channel ID here.

Don’t forget to add the Global variable in your wp-config.php file. Find your YouTube Developer Key here.

$GLOBALS['youtube'] = 'developer_key';

I’d recommend adding the code to adjust the iFrame.

Download the “google-api-php-client–PHP7.4” from this GitHub repository.

Have any questions or comments? Write them below!


Leave a Reply

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