Advertisement
hmbashar

Youtube Feed with shortcode

May 8th, 2025
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 5.50 KB | Software | 0 0
  1. <?php
  2. function fetch_youtube_videos_shortcode($atts) {
  3.     $atts = shortcode_atts([
  4.         'channel_id'   => '',
  5.         'playlist_id'  => '',
  6.         'max_results'  => 4,
  7.         'api_key'      => '',
  8.         'type'         => 'channel'
  9.     ], $atts);
  10.  
  11.     $api_key = $atts['api_key'];
  12.     $max     = intval($atts['max_results']);
  13.     $cache_key_success = 'youtube_cache_success_' . md5(serialize($atts));
  14.     $cache_key_error   = 'youtube_cache_error_' . md5(serialize($atts));
  15.  
  16.     // 🚀 Try wp_cache first (fastest)
  17.     $cached_videos = wp_cache_get($cache_key_success, 'youtube_videos');
  18.     if (!$cached_videos) {
  19.         $cached_videos = get_transient($cache_key_success); // fallback to transient
  20.         if ($cached_videos) {
  21.             // Save back to wp_cache for faster future loads
  22.             wp_cache_set($cache_key_success, $cached_videos, 'youtube_videos', 6 * HOUR_IN_SECONDS);
  23.         }
  24.     }
  25.  
  26.     if ($cached_videos) {
  27.         $body = $cached_videos;
  28.     } else {
  29.         // Check if error is cached (wp_cache first)
  30.         $cached_error = wp_cache_get($cache_key_error, 'youtube_videos');
  31.         if (!$cached_error) {
  32.             $cached_error = get_transient($cache_key_error);
  33.             if ($cached_error) {
  34.                 wp_cache_set($cache_key_error, $cached_error, 'youtube_videos', HOUR_IN_SECONDS);
  35.             }
  36.         }
  37.  
  38.         if ($cached_error) {
  39.             return esc_html($cached_error);
  40.         }
  41.  
  42.         // Build API URL
  43.         if ($atts['type'] === 'playlist' && $atts['playlist_id']) {
  44.             $url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId={$atts['playlist_id']}&maxResults={$max}&key={$api_key}";
  45.         } elseif ($atts['type'] === 'channel' && $atts['channel_id']) {
  46.             $url = "https://www.googleapis.com/youtube/v3/search?key={$api_key}&channelId={$atts['channel_id']}&part=snippet,id&order=date&type=video&videoDuration=medium&maxResults={$max}";
  47.         } else {
  48.             return 'Invalid settings. Please check your shortcode attributes.';
  49.         }
  50.  
  51.         $response = wp_remote_get($url);
  52.  
  53.         if (is_wp_error($response)) {
  54.             $error_message = 'Unable to fetch videos. Please try again later.';
  55.             $error_cache_duration = apply_filters('youtube_videos_error_cache_time', HOUR_IN_SECONDS);
  56.             wp_cache_set($cache_key_error, $error_message, 'youtube_videos', $error_cache_duration);
  57.             set_transient($cache_key_error, $error_message, $error_cache_duration);
  58.             return $error_message;
  59.         }
  60.  
  61.         $body = json_decode(wp_remote_retrieve_body($response));
  62.  
  63.         if (isset($body->error)) {
  64.             $error_code    = $body->error->code ?? '';
  65.             $error_message = $body->error->message ?? 'YouTube API error occurred.';
  66.  
  67.             if (in_array($error_code, [403, 429])) {
  68.                 $error_message = 'YouTube API quota limit reached. Please check back later.';
  69.                 $quota_cache_duration = apply_filters('youtube_videos_quota_cache_time', DAY_IN_SECONDS);
  70.                 wp_cache_set($cache_key_error, $error_message, 'youtube_videos', $quota_cache_duration);
  71.                 set_transient($cache_key_error, $error_message, $quota_cache_duration);
  72.             } else {
  73.                 $error_cache_duration = apply_filters('youtube_videos_error_cache_time', HOUR_IN_SECONDS);
  74.                 wp_cache_set($cache_key_error, $error_message, 'youtube_videos', $error_cache_duration);
  75.                 set_transient($cache_key_error, $error_message, $error_cache_duration);
  76.             }
  77.  
  78.             return esc_html($error_message);
  79.         }
  80.  
  81.         if (!empty($body->items)) {
  82.             $success_cache_duration = apply_filters('youtube_videos_success_cache_time', 6 * HOUR_IN_SECONDS);
  83.             wp_cache_set($cache_key_success, $body, 'youtube_videos', $success_cache_duration);
  84.             set_transient($cache_key_success, $body, $success_cache_duration);
  85.         } else {
  86.             $empty_cache_duration = apply_filters('youtube_videos_empty_cache_time', 30 * MINUTE_IN_SECONDS);
  87.             wp_cache_set($cache_key_error, 'No videos found.', 'youtube_videos', $empty_cache_duration);
  88.             set_transient($cache_key_error, 'No videos found.', $empty_cache_duration);
  89.             return 'No videos found.';
  90.         }
  91.     }
  92.  
  93.     // 🔥 Generate HTML
  94.     $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;">';
  95.  
  96.     foreach ($body->items as $item) {
  97.         $snippet = $item->snippet;
  98.         $video_id = ($atts['type'] === 'playlist') ? $snippet->resourceId->videoId : ($item->id->videoId ?? '');
  99.         if (!$video_id) continue;
  100.  
  101.         $title = esc_html($snippet->title);
  102.         $thumb = esc_url($snippet->thumbnails->medium->url);
  103.         $link = "https://www.youtube.com/watch?v={$video_id}";
  104.  
  105.         $html .= "<div style='flex:1 0 24%; max-width:24%;'>
  106.                    <a href='{$link}' target='_blank' style='text-decoration:none;color:#000;'>
  107.                        <img src='{$thumb}' alt='{$title}' style='width:100%;border-radius:8px;'>
  108.                        <p style='margin-top:8px;font-weight:600;font-size:19px;font-family:\"Fira Sans Condensed\", sans-serif;'>{$title}</p>
  109.                    </a>
  110.                  </div>";
  111.     }
  112.  
  113.     $html .= '</div>';
  114.  
  115.     return $html;
  116. }
  117. add_shortcode('youtube_videos', 'fetch_youtube_videos_shortcode');
  118.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement