我正在用可湿性粉剂和PHP工作,并试图减少我的加载时间的函数,抓取一堆数据.我认为瞬变语句可以工作,并且(如下面所示)我在瞬变语句下加载了课程查询,但是它不能在Foreach语句上工作,或者更确切地说,我不知道如何正确地设置它才能工作.
让一切变慢的主要代码是Foreach语句,该语句获取每个主题的Vimeo视频id,通过Vimeo_api()函数运行它,然后获取视频的持续时间,然后将其附加到数组中的主题id.
从技术上讲,我不必使用Get_Vimeo_Duration_All_Coursees()函数(which calls all the courses/lessons/topics),而是在加载时从每个主题获取Vimeo ID,因为这是我一开始使用的方法,它确实有效,但不幸的是它增加了我的页面加载时间.我的 idea 是,如果我可以加载数组中的所有持续时间,并将每个持续时间附加到主题ID,那么我就不必在每次想要获得视频持续时间时调用Vimeo_API()函数.我可以做的更多,只需每天更新$Vimeo变量一次,然后在$Vimeo变量中搜索主题ID以获得Vimeo持续时间.
So I guess I'm wondering if I'm heading in the right direction or if you know of a better way to go about it?个
Is there a way that I can store the $vimeo variable with all the values inside of it so that the vimeo_api() function doesn't have to run each time?个
任何帮助都是令人惊叹的!谢谢
function get_vimeo_duration_all_courses($vimeo)
{
$courses = get_transient('all_courses');
if (false === $courses) {
$courses = new WP_Query(array(
'posts_per_page' => -1,
'post_type' => 'sfwd-courses',
'no_found_rows' => true,
'cache_results' => true,
'ignore_sticky_posts' => true,
'fields' => 'ids',
)); //Grabs all the courses
set_transient('all_courses', $courses, (24 * HOUR_IN_SECONDS));
}
$vimeo = get_transient('all_vimeo_durations');
if (false === $vimeo) {
$vimeo = array();
foreach ($courses->posts as $course_id) {
$lessons = learndash_course_get_lessons($course_id); //Gets all the lessons under the course
foreach ($lessons as $lesson) {
$topics = learndash_course_get_topics($course_id, $lesson->ID); //Gets all the topics under the lesson
foreach ($topics as $topic) {
$vimeoVideo = get_field('lesson_video', $topic->ID);
if (!empty($vimeoVideo)) { //Looks at each topic and determines whether it has a vimeo video or not
$vimeoDuration = vimeo_api($vimeoVideo); //If true, it runs the vimeo ID through the vimeo_api() function (THIS IS WHERE IT BECOMES SLOW)
$vimeo[$topic->ID] = $vimeoDuration;
}
}
}
}
set_transient('all_vimeo_durations', $vimeo, (24 * HOUR_IN_SECONDS));
}
return $vimeo;
}
function show_vimeo_duration($topicID) {
return $vimeo[$topicID]; //Returns the value of the vimeo_api() function that matches the topicID
}
下面是我获取Vimeo API并返回视频时长的地方
function vimeo_api($id)
{
try {
$authorization = 'CODELEFTOUTONPURPOSE';
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => "https://api.vimeo.com/videos/$id?fields=duration",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Bearer {$authorization}",
"cache-control: no-cache",
),
));
$res = curl_exec($ch);
$obj = json_decode($res, true);
return $obj['duration'];//Returns the duration of the video
} catch (Exception $e) {
return "0";
}
}