A post scheduler for Pureblog CMS
I have written a simple post scheduler for Pureblog CMS.
This works super simple and has the code change the draft status to published when the time is right. To do so you create a new post as you normally would. For the date set when the post should be published and leave the status as Draft. Save the post and wait. By default this mod checks for drafts every 2 hours.
How to set it up
This requires 2 file edits.
If you haven't already, create the file /content/functions.php.
In it add the following code to the bottom of the file.
/* -------------------------
Post scheduler
Usage: Set a post to draft with a future date
------------------------- */
function post_scheduler($files_to_check = 10, $interval = 2) {
$timerfile = PUREBLOG_BASE_PATH . '/content/scheduler.tmp';
$now = time();
$interval = $interval * 3600; // Turn hours into seconds
if(!file_exists($timerfile) OR ($now - $interval) < filemtime($timerfile)) {
$files = glob(PUREBLOG_POSTS_PATH . "/*.md");
$files = array_slice($files, -$files_to_check);
$config = load_config();
foreach($files as $file) {
$parsed = parse_post_file($file);
$front = $parsed['front_matter'];
if($front['status'] == 'draft') {
$dt = parse_post_datetime_with_timezone($front['date'], $config);
$timestamp = $dt ? $dt->getTimestamp() : 0;
if($timestamp <= $now) {
$front['status'] = 'published';
$frontLines = array();
foreach ($front as $key => $value) {
if ($key === 'tags') {
$value = '[' . implode(', ', $value) . ']';
}
$frontLines[] = $key . ': ' . $value;
}
$body = "---\n".implode("\n", $frontLines) . "\n---\n\n" . ltrim($parsed['content']) . "\n";
file_put_contents($file, $body);
}
}
}
touch($timerfile);
}
}
This code loops through the last N files (10 by default) and checks if the post is a draft. If it is, it checks if the date is no longer in the future.
If it isn't, it changes the draft status to published. Simple and effective.
Next if you haven't, create the /content/includes/footer.php file and add this to the end of the file.
<?php
// Post scheduler
// Usage: Check the 10 latest files, every 2 hours. Adjust as needed.
post_scheduler(10, 2);
?>
This is the trigger. Since the footer is loaded on every page, this is a mostly reliable way to run custom code. This of-course relies on people visiting your website. If nobody ever visits, the trigger won't work.
Here you have 2 options:
- The first, 10, tells the script to check the newest 10 files.
If you have more than 10 drafts on the regular, increase this number as needed. - The second value is the interval to check. This is 2 hours by default.
If you have a quiet blog and don't post new stuff that often, a lower interval (higher number) is probably fine. Maybe every 24 hours. If you schedule posts for every hour then 1 (one) hour makes more sense.
And that's it. There is a timer file, which is stored as scheduler.tmp in the /content folder. The file's modification date determines the interval.
Have fun!