“A picture is worth a thousand words”
Moving pictures are even better! Thus, a while ago a friend asked me to help her show the most recent three videos from her YouTube channel on her website. Of course, I could have told her to copy and paste the YouTube URL into the editor, as WordPress provides 30+ embeds put of the box. This solution, however, would require that every time she uploads a video to YouTube, she would then have to manually add the video to her WordPress site.
Instead, I decided using the YouTube API and suggested to pull the videos automatically from her channel and playlist. This avoids manual effort and ensures that the latest videos are always visible on the site. Luckily implementing the YouTube API with WordPress is as easy as pie. I created the following code to show the latest three videos from her YouTube channel on her site:
https://gist.github.com/nielslange/5e1ec4c756dd04a4bb69841aef89ded5
Of course, requirements change over time. In the meantime, she created 30+ videos and wants to handpick three videos that should be shown on the homepage.
I suggested to create a separate playlist for the homepage videos and show the videos of this playlist instead of the videos of her channel. To reflect the new requirements I changed the code as follows:
https://gist.github.com/nielslange/3c9b0e601d16392eb262430e0bf34078
Also, she created a private YouTube playlist, to ensure that this playlist will not show within her YouTube playlists, but the videos can be accessed publicly.
Resources
- https://developer.wordpress.org/reference/functions/wp_remote_get/
- https://developer.wordpress.org/reference/functions/wp_remote_retrieve_body/
- http://php.net/manual/en/function.json-decode.php
- https://developers.google.com/youtube/v3/docs/playlists
- https://developers.google.com/youtube/v3/docs/search
- https://developers.google.com/youtube/player_parameters