请知悉:本文最近一次更新为 10年 前,文中内容可能已经过时。

我的博客都是有时间了写不少,然后定时发布,一天一篇,这样在忙的时候也可以保证更新频率。之前一直是手动的,最近琢磨也许可以通过修改WordPress的一些代码实现自动匹配时间并定时文章的功能,经过尝试,自己通过修改wp-include下的post.php文件实现的功能不是很顺手。再搜索发现,原来网上已经有人给出了实现这一功能的代码,在主题的function.php中添加如下代码即可实现让WordPress每篇文章的发布时间至少间隔24小时的功能。我是通过https://www.wpdaxue.com/post-publication-spacing-in-minutes.html和https://WordPress.stackexchange.com/questions/104677/how-to-prevent-posts-from-being-published-too-close-to-each-other/找到这些代码的。

function force_time_between_posts($data, $postarr) {
global $wpdb;
if (empty($postarr['ID'])) return $data;

$latest = $wpdb->get_var("
SELECT post_date
FROM {$wpdb->posts}
WHERE post_status IN('future','publish')
AND post_type = 'post'
AND ID != {$postarr['ID']}
ORDER BY post_date DESC
LIMIT 1");
$distance = 1440; // 文章间隔分钟数
$latest = strtotime($latest);
$current = strtotime($data['post_date']);
if ($latest < $current) {
$diff = $current - $latest;
} else {
$diff = 0;
}

if ($diff >= 0 && $diff < ($distance * 60) && $current<time()+($distance * 60) && $current+($distance * 60)>=time()) { #首先,文章发布时间要小于现在的时间加你的时间间隔,其次,文章发布时间+你的时间间隔要大于现在的时间(未来的),且文字发布时间和最新文章发布时间的时间间隔要大于0小于你的时间间隔,才会生效
#上面的if我添加了个判定修正了编辑未来的文章时间会继续推后的BUG
$new_date = $latest + ($distance * 60);
$date = date('Y-m-d H:i:s',$new_date);
$date_gmt = get_gmt_from_date($date);
$data['post_date'] = $date;
$data['post_date_gmt'] = $date_gmt;
$data['post_status'] = 'future';
}
return $data;
}
add_action('wp_insert_post_data','force_time_between_posts',1,2);

修正了一些BUG,编辑过去的文章时间不会变动。


如您从本文得到了有价值的信息或帮助,请考虑扫描文末二维码捐赠和鼓励。

尊重他人劳动成果。转载请务必附上原文链接,我将感激不尽。


与《让WordPress文章发布自动推后到最新一篇文章之后的时间》相关的博文:


留言

avatar
😀
😀😁😂😅😭🤭😋😘🤔😰😱🤪💪👍👎🤝🌹👌