Skip to content

Instantly share code, notes, and snippets.

@billerickson
Last active February 1, 2018 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save billerickson/a3cac3877404c218aee3c7fae7f1077e to your computer and use it in GitHub Desktop.
Save billerickson/a3cac3877404c218aee3c7fae7f1077e to your computer and use it in GitHub Desktop.
<?php
/**
* YouTube Gallery
*
* @package CoreFunctionality
* @author Bill Erickson
* @since 1.0.0
* @license GPL-2.0+
**/
/**
* Youtube Gallery
*/
function ea_youtube_gallery_shortcode( $atts = array() ) {
$atts = shortcode_atts( array(
'user' => false
), $atts, 'ea_youtube_gallery' );
// Only run if user is specified
if( empty( $atts['user'] ) ) {
return;
}
// Get Videos
$data = ea_get_youtube_videos( $user );
$output = '<div class="youtube-gallery">';
// Video Player
$output .= '<div class="youtube-gallery--player">';
$output .= '<h4>Video goes here</h4>';
$output .= '</div>';
// Video Listing
$output .= '<div class="youtube-gallery--listing">';
for( $i = 0; $i < 24; $i++ ) {
$class = 0 == $i ? 'item active' : 'item';
$output .= '<a href="#main-content" class="' . $class . '">';
$output .= '<span class="title">thumbnail goes here</span>';
$output .= '</a>';
}
$output .= '</div>';
$output .= '</div>';
return $output;
}
add_shortcode( 'ea_youtube_gallery', 'ea_youtube_gallery_shortcode' );
/**
* Get Youtube Videos
*
*/
function ea_get_youtube_videos( $user = '' ) {
if( empty( $user ) )
return;
$key = 'ea_youtube_gallery_' . sanitize_text_field( $user );
$data = get_transient( $key );
if( false === $data ) {
$channel = ea_get_youtube_channel( $user );
$url = add_query_arg( array(
'part' => 'snippet',
'channelId' => $channel,
'order' => 'date',
'maxResults' => 24,
'key' => EA_YOUTUBE_API_KEY,
), 'https://www.googleapis.com/youtube/v3/search' );
$data = wp_remote_retrieve_body( wp_remote_get( $url ) );
set_transient( $key, $data, DAY_IN_SECONDS );
}
return $data;
}
/**
* Get Youtube Channel
*
*/
function ea_get_youtube_channel( $user = '' ) {
if( empty( $user ) )
return;
$channels = get_option( 'ea_youtube_gallery_channels' );
if( empty( $channels ) || empty( $channels[ $user ] ) ) {
$url = add_query_arg(
array(
'forUsername' => esc_attr( $user ),
'part' => 'id',
'key' => EA_YOUTUBE_API_KEY,
),
'https://www.googleapis.com/youtube/v3/channels'
);
$response = wp_remote_get( $url );
$data = json_decode( wp_remote_retrieve_body( $response ) );
if( !empty( $data->items ) )
$channels[ $user ] = $data->items[0]->id;
else
$channels[ $user ] = false;
update_option( 'ea_youtube_gallery_channels', $channels );
}
return $channels[ $user ];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment