Automatically link youtube videos

You could try with a php function the following:

<?php
function getYouTubeVideosByTag($tag, $maxResults = 6) {
    $apiKey = '[your youtube API key]';
    $channelId = '[your-youtube-channel-ID';

    // Forza formato hashtag
    $query = urlencode('#' . $tag);

    $url = "https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&order=date&maxResults=$maxResults&q=$query&channelId=$channelId&key=$apiKey";

    $response = file_get_contents($url);

    if ($response === FALSE) {
        return [];
    }

    $data = json_decode($response, true);

    $videos = [];

    if (!empty($data['items'])) {
        foreach ($data['items'] as $item) {
            if (!isset($item['id']['videoId'])) continue;

            $videos[] = [
                'title' => $item['snippet']['title'],
                'videoId' => $item['id']['videoId'],
                'description' => $item['snippet']['description'],
                // 'thumbnail' => $item['snippet']['thumbnails']['medium']['url']
            ];
        }
    }

    return $videos;
}
?>

Obviously you have to link this function in every web page you want links your videos, and in these pages you can call that function by a code like this:

<?php
if (!empty($youtubetag)) {

    if (is_array($youtubetag)) {
        $query = implode(' OR ', array_map(fn($t) => '#' . $t, $youtubetag));
        $videos = getYouTubeVideos($query, 5);
    } else {
        $videos = getYouTubeVideosByTag($youtubetag, 3);
    }

    if (!empty($videos)) {
        ?>

        <section class="youtube-videos">
        <h2>🎙️ Our podcast (YouTube)</h2>

            <ul>
                <?php foreach ($videos as $video): ?>
                    <li class="podcast">🎙️
                        <a href="https://www.youtube.com/watch?v=<?= $video['videoId'] ?>"><strong><?= htmlspecialchars($video['title']) ?></strong></a>:
                       <?= htmlspecialchars(substr($video['description'], 0, 120), ENT_QUOTES | ENT_HTML5, 'UTF-8', false) ?>
                    </li>
                <?php endforeach; ?>
            </ul>
        </section>

        <?php
    }
}
?>

Finally, you should define, possibly in the head of each php page, where you want to link youtube videos, the variable $youtubetag:

$youtubetag="my tag";
or 
$youtubetag="['mytag1', 'mytag2']";

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *