WordPress:自动保存帖子每天晚上与预定的事件



我想在晚上用预定的事件保存每个帖子。因为我们有很多帖子,我想把这些帖子分成25个块。

这是我当前的代码:

function autosave_posts() {
// Set up query arguments
$args = array(
'post_type'      => 'post',
'post_status'    => 'publish',
'posts_per_page' => 25,
'orderby'        => 'ID',
'order'          => 'ASC',
'paged'          => 1, // Start with first page
);
// Loop through posts until all have been updated
while ( $posts = new WP_Query( $args ) ) {
if ( $posts->have_posts() ) {
while ( $posts->have_posts() ) {
$posts->the_post();
wp_update_post( array( 'ID' => get_the_ID() ) );
}
wp_reset_postdata();
// Increment the paged argument to get the next set of posts
$args['paged']++;
} else {
// There are no more posts, so we're done
break;
}
}
}
// Schedule the event if it doesn't already exist
if ( ! wp_next_scheduled( 'autosave_posts' ) ) {
wp_schedule_event( strtotime( '04:00:00' ), 'daily', 'autosave_posts' );
}
// Hook the function to the scheduled event
add_action( 'autosave_posts', 'autosave_posts' );

我在未来用2分钟的时间进行了测试。但不幸的是,这些帖子没有被保存。

我用cron Crontrol检查了cron事件,看到事件在列表中。所以我运行了它

一些帖子被保存了。但并不是所有的函数都被超过了,因为函数的最大执行时间为60秒。

我在while环后添加了sleep(5)。但是最大执行时间的问题仍然存在。

现在我有两个问题:

  1. 函数是否正确并可以运行?是我的"未来时光"吗?错了吗?我不确定wp_schedule_event函数使用的时间。
  2. 是否有办法防止maximum execution time的问题?我能以任何方式拆分这个函数吗?我认为25个帖子块已经足够了

尝试在while语句之后调用set_time_limit(60)。它会将每次循环的时间限制重置为一分钟,减少超时的机会。

避免睡眠()。它毫无理由地占用了一个稀缺的网络服务器进程。而且,睡觉不计入时间限制。

但是,一些主机施加了一个整体的,不可重置的时间限制。在这种情况下,你需要将批量大小从25个减少到更小。

你没有说为什么你这样做。也许有一种更有效的方法来做你需要做的事情。但是,如果不知道为什么,很难给你具体的建议。

最新更新