我编写了一个PHP脚本,以编程方式从Google日历事件创建自定义帖子,并编写了一个操作挂钩,用于清除所有现有事件并用当前事件重新填充。当我单击已添加到视图中的按钮时,效果很好。然而,当我尝试将钩子作为cron作业来执行时(使用WP控制插件),它会清除现有的帖子,但不会创建新的帖子。我从调试中得到的唯一输出是一个关于上下文帮助被弃用的警告,我认为这与此无关,但我当然可能是错的。
以下是代码(相关部分):
function create_event_posts() {
//calendar-ids and parameters are stored in variables outside of the function for reference in other functions
global $calendarIds;
global $optParams;
//delete existing posts <-- This works fine! :)
$allEvents = get_posts(array(\'post_type\' => \'event\', \'numberposts\' => -1));
foreach ($allEvents as $eachEvent) {
wp_delete_post($eachEvent -> ID, true);
}
//call to google calendar script
require_once ABSPATH . \'path/to/vendor/autoload.php\';
$client = new Google_Client();
$client -> setApplicationName(\'customCalendar\');
$client -> setAuthConfig(ABSPATH . \'path/to/credentials.json\');
$client = getClient();
$service = new Google_Service_Calendar($client);
//collecting all the events
foreach ($calendarIds as $calendarId) {
$results = $service -> events -> listEvents($calendarId, $optParams);
$events[] = $results -> getItems();
}
$events = flatten($events);
foreach ($events as $event) {
$eventContent = $eventTitle = $eventColor = $calendarTitle = \'\';
$calendarTitle = $event -> organizer -> displayName;
$eventContent = apply_filters(\'the_content\', $event -> getDescription());
$start = $event -> start -> dateTime;
$end = $event -> end -> dateTime;
$fmt = new \\IntlDateFormatter(\'nb-NO\', NULL, NULL);
$fmt -> setPattern(\'EEEE d. MMMM\');
$outputDate = $fmt -> format(strtotime($start));
$outputStart = date(\'H:i\', strtotime($start));
$outputEnd = date(\'H:i\', strtotime($end));
if (empty($start)) {
$start = $event -> start -> date;
}
$eventPost = array(
\'post_author\' => 1,
\'post_date\' => date(\'Y-m-d H:i:s\'),
\'post_content\' => $eventContent,
\'post_title\' => $eventTitle,
\'post_excerpt\' => $outputDate . \', kl. \' . $outputStart . \' – \' . $outputEnd,
\'post_status\' => \'publish\',
\'post_type\' => \'event\',
\'post_category\' => array($eventCategory), //I cut out the part where this variable is defined, to save space
\'meta_input\' => array(
\'_EventStartDate\' => $start,
\'_Room\' => $calendarTitle,
),
);
if (!post_exists($eventTitle, $eventContent, \'\', \'event\')) {
$post_ID = wp_insert_post($eventPost);
}
}
}
钩子是:
add_action(\'admin_post_create_event_posts\', \'create_event_posts\');