Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function fetch_youtube_videos_shortcode($atts) {
- $atts = shortcode_atts([
- 'channel_id' => '',
- 'playlist_id' => '',
- 'max_results' => 4,
- 'api_key' => '',
- 'type' => 'channel'
- ], $atts);
- $api_key = $atts['api_key'];
- $max = intval($atts['max_results']);
- $cache_key_success = 'youtube_cache_success_' . md5(serialize($atts));
- $cache_key_error = 'youtube_cache_error_' . md5(serialize($atts));
- // Try wp_cache first
- $cached_videos = wp_cache_get($cache_key_success, 'youtube_videos');
- if (!$cached_videos) {
- $cached_videos = get_transient($cache_key_success);
- if ($cached_videos) {
- wp_cache_set($cache_key_success, $cached_videos, 'youtube_videos', 6 * HOUR_IN_SECONDS);
- }
- }
- if ($cached_videos) {
- $body = $cached_videos;
- } else {
- // Check if error is cached
- $cached_error = wp_cache_get($cache_key_error, 'youtube_videos');
- if (!$cached_error) {
- $cached_error = get_transient($cache_key_error);
- if ($cached_error) {
- wp_cache_set($cache_key_error, $cached_error, 'youtube_videos', HOUR_IN_SECONDS);
- }
- }
- if ($cached_error) {
- return esc_html($cached_error);
- }
- // Build API URL
- if ($atts['type'] === 'playlist' && $atts['playlist_id']) {
- $url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId={$atts['playlist_id']}&maxResults=50&key={$api_key}";
- } elseif ($atts['type'] === 'channel' && $atts['channel_id']) {
- // Removed videoDuration param here
- $url = "https://www.googleapis.com/youtube/v3/search?key={$api_key}&channelId={$atts['channel_id']}&part=snippet,id&order=date&type=video&maxResults=20";
- } else {
- return 'Invalid settings. Please check your shortcode attributes.';
- }
- $response = wp_remote_get($url);
- if (is_wp_error($response)) {
- $error_message = 'Unable to fetch videos. Please try again later.';
- $error_cache_duration = apply_filters('youtube_videos_error_cache_time', HOUR_IN_SECONDS);
- wp_cache_set($cache_key_error, $error_message, 'youtube_videos', $error_cache_duration);
- set_transient($cache_key_error, $error_message, $error_cache_duration);
- return $error_message;
- }
- $body = json_decode(wp_remote_retrieve_body($response));
- // For playlist type: sort by date & limit
- if ($atts['type'] === 'playlist' && !empty($body->items)) {
- $body->items = array_filter($body->items, function($item) {
- return isset($item->snippet->publishedAt);
- });
- usort($body->items, function($a, $b) {
- return strtotime($b->snippet->publishedAt) - strtotime($a->snippet->publishedAt);
- });
- $body->items = array_slice($body->items, 0, $max);
- }
- // For channel type: filter out Shorts based on duration
- if ($atts['type'] === 'channel' && !empty($body->items)) {
- $video_ids = [];
- foreach ($body->items as $item) {
- $video_id = $item->id->videoId ?? '';
- if ($video_id) {
- $video_ids[] = $video_id;
- }
- }
- if (!empty($video_ids)) {
- $videos_url = "https://www.googleapis.com/youtube/v3/videos?key={$api_key}&id=" . implode(',', $video_ids) . "&part=contentDetails";
- $videos_response = wp_remote_get($videos_url);
- if (!is_wp_error($videos_response)) {
- $videos_body = json_decode(wp_remote_retrieve_body($videos_response));
- $durations = [];
- foreach ($videos_body->items as $video_item) {
- $durations[$video_item->id] = $video_item->contentDetails->duration;
- }
- // Filter out Shorts (<= 60 sec)
- $filtered_items = [];
- foreach ($body->items as $item) {
- $video_id = $item->id->videoId ?? '';
- if (!$video_id || !isset($durations[$video_id])) continue;
- try {
- $interval = new DateInterval($durations[$video_id]);
- $seconds = ($interval->h * 3600) + ($interval->i * 60) + $interval->s;
- } catch (Exception $e) {
- $seconds = 0; // Fallback if parsing fails
- }
- if ($seconds > 60) { // Keep videos longer than 60 sec (not Shorts)
- $filtered_items[] = $item;
- }
- }
- // Slice to max results
- $body->items = array_slice($filtered_items, 0, $max);
- }
- }
- }
- if (isset($body->error)) {
- $error_code = $body->error->code ?? '';
- $error_message = $body->error->message ?? 'YouTube API error occurred.';
- if (in_array($error_code, [403, 429])) {
- $error_message = 'YouTube API quota limit reached. Please check back later.';
- $quota_cache_duration = apply_filters('youtube_videos_quota_cache_time', DAY_IN_SECONDS);
- wp_cache_set($cache_key_error, $error_message, 'youtube_videos', $quota_cache_duration);
- set_transient($cache_key_error, $error_message, $quota_cache_duration);
- } else {
- $error_cache_duration = apply_filters('youtube_videos_error_cache_time', HOUR_IN_SECONDS);
- wp_cache_set($cache_key_error, $error_message, 'youtube_videos', $error_cache_duration);
- set_transient($cache_key_error, $error_message, $error_cache_duration);
- }
- return esc_html($error_message);
- }
- if (!empty($body->items)) {
- $success_cache_duration = apply_filters('youtube_videos_success_cache_time', 6 * HOUR_IN_SECONDS);
- wp_cache_set($cache_key_success, $body, 'youtube_videos', $success_cache_duration);
- set_transient($cache_key_success, $body, $success_cache_duration);
- } else {
- $empty_cache_duration = apply_filters('youtube_videos_empty_cache_time', 30 * MINUTE_IN_SECONDS);
- wp_cache_set($cache_key_error, 'No videos found.', 'youtube_videos', $empty_cache_duration);
- set_transient($cache_key_error, 'No videos found.', $empty_cache_duration);
- return 'No videos found.';
- }
- }
- // Generate HTML
- $html = '<div class="youtube-video-widget" style="display:flex; flex-wrap:nowrap; gap:20px; overflow-x:auto; justify-content:space-between; font-family:\'Fira Sans Condensed\', sans-serif;">';
- foreach ($body->items as $item) {
- $snippet = $item->snippet;
- $video_id = ($atts['type'] === 'playlist') ? $snippet->resourceId->videoId : ($item->id->videoId ?? '');
- if (!$video_id) continue;
- $title = esc_html($snippet->title);
- $thumb = esc_url($snippet->thumbnails->medium->url);
- $link = "https://www.youtube.com/watch?v={$video_id}";
- $html .= "<div style='flex:1 0 24%; max-width:24%;'>
- <a href='{$link}' target='_blank' style='text-decoration:none;color:#000;'>
- <img src='{$thumb}' alt='{$title}' style='width:100%;border-radius:8px;'>
- <p style='margin-top:8px;font-weight:600;font-size:19px;font-family:\"Fira Sans Condensed\", sans-serif;'>{$title}</p>
- </a>
- </div>";
- }
- $html .= '</div>';
- return $html;
- }
- add_shortcode('youtube_videos', 'fetch_youtube_videos_shortcode');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement