Yacc
Добавить в конец файла functions.php активной темы
function yacc_save_post ($post_id) {
$post = get_post($post_id);
if ($post->post_status !== 'publish' or wp_is_post_revision($post->ID)) return;
preg_match('/http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?[\w\?=]*)?/', $post->post_content, $m);
$video_id = $m[1];
if ($video_id === get_post_meta($post->ID, 'video_id', true) or ! $related_videos = yacc_related_videos($video_id)) return;
$links = ['<ul class="related _posts">'];
remove_action('save_post', 'yacc_save_post', 99);
foreach ($related_videos as $video) {
$p = get_page_by_title($video['snippet']['title'], OBJECT, 'post');
if ($p instanceof WP_Post) continue;
$id = wp_insert_post([
'post_author' => $post->post_author,
'post_content' => 'https://www.youtube.com/watch?v=' . $video['id']['videoId'],
'post_title' => $video['snippet']['title'],
'post_status' => 'publish',
'post_type' => 'post'
]);
update_post_meta($id, 'video_id', $video['id']['videoId']);
$links[] = '<li><a href="' . get_permalink($id) . '">' . $video['snippet']['title'] . '</a></li>';
}
$links[] = '</ul>';
wp_update_post(['ID' => $post_id, 'post_content' => $post->post_content . implode('', $links)]);
update_post_meta($post->ID, 'video_id', $video_id);
add_action('save_post', 'yacc_save_post', 99);
}
function yacc_related_videos ($id, $limit = 5) {
$params = [
'key' => '
API_KEY',
'part' => 'snippet',
'type' => 'video',
'maxResults' => $limit,
'relatedToVideoId' => $id
];
$url = 'https://www.googleapis.com/youtube/v3/search?' . http_build_query($params);
$items = [];
$response = wp_remote_get($url);
if (is_array($response) and isset($response['body'])) {
$body = json_decode($response['body'], true);
if (isset($body['items'])) {
$items = $body['items'];
}
}
return $items;
}
add_action('save_post', 'yacc_save_post', 99);
API_KEY -
https://console.developers.google.com/apis/api/youtube/overview.
Написано на коленке, проверено плохо, ненавижу вордпресс.