首页 问答 正文

WordPress文章如何定时发布?

注册会员 / 悠然自学 / 2023-06-12/ 浏览 147 次

在WordPress中,可以使用函数wp_schedule_single_event来定时发布文章。以下是一个示例代码:

// 创建一个新的文章
$new_post = array(
    'post_type'     => 'post',
    'post_title'    => '定时发布的文章',
    'post_content'  => '这是一篇定时发布的文章。',
    'post_status'   => 'draft', // 设置状态为草稿
);

// 插入新的文章,并获取其ID
$post_id = wp_insert_post($new_post);

// 获取当前时间
$current_time = current_time('timestamp');

// 设置定时发布的时间(当前时间的一小时后)
$delay_time = $current_time + 3600;

// 使用wp_schedule_single_event函数来创建一个定时事件
wp_schedule_single_event($delay_time, 'publish_post_event', array($post_id)); 

在上面的代码中,我们首先创建一个新的文章并将其状态设置为草稿。然后,我们获取当前时间并设置一个延迟时间(例如1小时后)。最后,我们使用wp_schedule_single_event函数创建一个定时事件,并指定要触发的函数名为publish_post_event。此函数需要传递文章ID作为参数。

你需要将上述代码添加到WordPress主题的functions.php文件中,然后创建一个新的函数publish_post_event,并在该函数中更新文章状态为已发布。示例代码如下:

// 定义触发的函数
function publish_post_event($post_id) {
    // 更新文章状态为已发布
    wp_update_post(array('ID' => $post_id, 'post_status' => 'publish'));
} 

这样,当定时事件触发时,publish_post_event函数将被调用,并将文章状态更新为已发布。

大家谈论
    我的见解