我对Wordpress很陌生,但对Web开发不是新手。
我正在创建一个基于 wordpress 的网站,我有一个包含 450 多个视频的 youtube 频道,我想为每个视频创建一个帖子。
我已经有了一个适用于 Youtube API Data V3 的 API KEY 和正确的网址来展示我的视频。此外,我读到了这个伟大的wp_insert_post,它似乎完全符合我需要做的事情。
我想知道的是将我的代码放在哪里?这将非常简单,例如:客户端:
$.get('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=UUbRrCTEldKci2yWosUukSQQ&key=APIKEY');
.success(function(data){
data.forEach(function(vid){
$.post('myPhpPostInserter.php', vid);
});
});
服务器端:
<?php
$myPost['title'] = $_POST['vid_title'];
//some more mapping on the $myPost array...
wp_insert_post($myPost);
这将是一项一次性工作,因此我正在尝试实现这个快速的客户端-服务器解决方案。
通常的位置是在函数中.php在您的主题或子主题中(建议使用,因为更新将覆盖主题中的自定义代码)或您自己创建的插件(pluginname.php)。
我在下面提出了实现这一目标的最佳方法,它根本不是客户端,但我相信这将更适合您。基本上在每个页面加载时,代码将运行并上传接下来的 50 个视频(如果超时,请减少下图 - 请参阅评论)(您应该在上传所有视频时删除代码)。
如果有任何错误,请原谅我,请在 txt 文件上键入此内容。我也不知道返回的 json 的结构,我没有要检查的 api 密钥,您需要在 for 循环中更新正确的结构才能获得您想要的数据......
function upload_videos(){
if(!get_option( 'vid_count' ) ){
$x=0;
update_option( 'vid_count', $x );
} else {
$x= (int) get_option('vid_count');
}
//might as well cache the file to speed things up
if( !file_exists ( 'videos.json' )){
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=5000&playlistId=UUbRrCTEldKci2yWosUukSQQ&key=APIKEY');
$json = curl_exec($ch);
curl_close($ch);
$videos = fopen("videos.json", "w") or die("Unable to open file!");
fwrite($videos, $json);
fclose($videos);
unset($videos);
}
$videos = fopen("videos.json", "r");
$videos = json_decode($videos);
//get the structure of the array here and update the foreach loop to the right place in the object...
//remove this code when ready.....
var_dump($videos);
exit;
//end remove.....
/*
remember to update to the correct values....
we will do 50 at a time
*/
$max= $x+50; // adjust 50 downwards if needed
if($max > count( $videos['list'] ) )
$max= count( $videos['list'] );
if($max > $x)
return;
update_option('vid_count', $max );
for($v=$x; $v<=$max; $v++){
$id= wp_insert_post(
array(
'post_status'=>'publish',
'post_type'=>'video', //higher recommended to create a cpt and post template for this..
'post_title'=> $videos['list'][$v]->title, // sample --- dont know the format of the returned object
'content'=> 'whatever you want or html for the video, etc................'
));
//save the url into the metadata of the post....we can use this in templates to show the video....
update_post_meta($id, '_vid_url', $videos['list'][$v]->video_url);// sample --- dont know the format of the returned object
}
}
add_action('init', 'upload_videos');