使用采集插件采集到文章以后,并不想让它立刻发布,而是希望它在规定的时间点发布。这样做经验上来看是有利于SEO的。
1.应在主题/插件激活时注册,并添加deactivation_hook来清理任务。
// 在主题的functions.php或插件中
register_activation_hook(__FILE__, 'zrz_activate_schedule');
function zrz_activate_schedule() {
if (!wp_next_scheduled('zrz_post_schedule_event')) {
$timestamp = strtotime('tomorrow midnight', current_time('timestamp'));
wp_schedule_event($timestamp, 'daily', 'zrz_post_schedule_event');
}
}
2.使用WordPress内置函数current_time(‘timestamp’)自动处理时区
$timestamp = strtotime('tomorrow midnight', current_time('timestamp'));
3.明确排序依据,并限制字段提升性能
$args = array(
'orderby' => 'post_date', // 按创建时间排序
'order' => 'ASC',
'post_type' => 'post',
'post_status' => 'draft',
'posts_per_page' => 10,
'fields' => 'ids', // 仅获取ID
);
4.添加条件排除已计划发布的文章
$args['meta_query'] = array(
array(
'key' => '_wp_trash_meta_time',
'compare' => 'NOT EXISTS'
)
);
5.记录任务执行情况以便排查
foreach ($posts as $post_id) {
$result = wp_update_post(array('ID' => $post_id, 'post_status' => 'publish'));
if (is_wp_error($result)) {
error_log('Failed to publish post: ' . $post_id);
}
}
完整代码
// 注册激活钩子安排任务
register_activation_hook(__FILE__, 'zrz_activate_schedule');
function zrz_activate_schedule() {
if (!wp_next_scheduled('zrz_post_schedule_event')) {
$timestamp = strtotime('tomorrow midnight', current_time('timestamp'));
wp_schedule_event($timestamp, 'daily', 'zrz_post_schedule_event');
}
}
// 停用时清除任务
register_deactivation_hook(__FILE__, 'zrz_deactivate_schedule');
function zrz_deactivate_schedule() {
wp_clear_scheduled_hook('zrz_post_schedule_event');
}
// 执行每日发布
add_action('zrz_post_schedule_event', 'zrz_post_schedule_do_this_daily');
function zrz_post_schedule_do_this_daily() {
$args = array(
'orderby' => 'post_date',
'order' => 'ASC',
'post_type' => 'post',
'post_status' => 'draft',
'posts_per_page' => 10,
'fields' => 'ids',
'meta_query' => array(
array(
'key' => '_wp_trash_meta_time',
'compare' => 'NOT EXISTS'
)
)
);
$post_ids = get_posts($args);
foreach ($post_ids as $post_id) {
$result = wp_update_post(array(
'ID' => $post_id,
'post_status' => 'publish'
));
if (is_wp_error($result)) {
error_log("发布文章 {$post_id} 失败: " . $result->get_error_message());
}
}
}
其他建议:
- 使用服务器Cron替代WP-Cron:在
wp-config.php
中禁用默认WP-Cron,通过服务器添加真实Cron任务:
define('DISABLE_WP_CRON', true);
然后添加Cron任务执行:
0 0 * * * curl -s http://yoursite.com/wp-cron.php?doing_wp_cron > /dev/null 2>&1
- 通知机制:可添加邮件或管理员通知,当成功发布或出现错误时提醒。
» 标题: Wordpress采集到的草稿文章每天定时发布» 本文来自热心的夹友 Niuma 提供。