/*
Plugin Name: YouTube Video Downloader and View Analysis
Description: Detects YouTube embeds in posts, displays download buttons, and shows view analysis for the last 7 days.
Version: 1.2
Author: Your Name
*/
function yvd_add_download_buttons_and_view_analysis($content) {
// Your YouTube API key
$api_key = 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8';
// Regular expression to match YouTube iframe within a div with class "video-embed"
$pattern = '/(
.*?
<\/iframe>.*?<\/div>)/is';
// Check if there is any match
if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
// Extract video ID and original div with iframe
$original_div = $match[1];
$video_id = $match[2];
$video_url = "https://www.youtube.com/watch?v=" . $video_id;
$download_url = "https://www.fad.su/video/youtube-video-downloader/?url=" . urlencode($video_url);
// Fetch view data for the last 7 days
$view_data = get_youtube_view_data($video_id, $api_key);
$view_analysis_html = generate_view_analysis_html($view_data);
// Create download buttons HTML
$buttons_html = '
' . $view_analysis_html . '
';
// Replace original div with iframe with the div plus download buttons HTML
$replacement = $original_div . $buttons_html;
$content = str_replace($original_div, $replacement, $content);
}
}
return $content;
}
function get_youtube_view_data($video_id, $api_key) {
// Define the endpoint for fetching statistics
$endpoint = "https://www.googleapis.com/youtube/v3/videos?part=statistics&id=$video_id&key=$api_key";
// Fetch data from YouTube API
$response = wp_remote_get($endpoint);
if (is_wp_error($response)) {
return [];
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (isset($data['items'][0]['statistics'])) {
$viewCount = $data['items'][0]['statistics']['viewCount'];
// Placeholder for 7-day view analysis, you should adjust the fetching method to get daily views
return ['viewCount' => $viewCount, 'dailyViews' => [100, 200, 150, 180, 220, 300, 250]];
} else {
return [];
}
}
function generate_view_analysis_html($view_data) {
if (empty($view_data)) {
return 'No view data available.
';
}
$dailyViews = $view_data['dailyViews'];
$html = '
View Analysis for Last 7 Days
Date |
Views |
';
for ($i = 0; $i < 7; $i++) {
$date = date('Y-m-d', strtotime("-$i days"));
$views = $dailyViews[$i];
$html .= "$date | $views |
";
}
$html .= '
';
return $html;
}
// Hook the function to 'the_content' filter
add_filter('the_content', 'yvd_add_download_buttons_and_view_analysis');