Skip to main content

Publishing Silverstripe pages via Cron

This blog post might be outdated!
This blog post was published more than one year ago and might be outdated!
· 2 min read
Stephan Hochdörfer
Head of IT Business Operations

As I have written before we moved from Wordpress to Silverstripe. The Silverstripe blog module has all the functionally needed to be used on a daily basis. However I was missing one particular feature of Wordpress: I want to be able to automatically publish blog posts via Cron. After some research it turned out that Silverstripe supports so-called BuildTasks which can be called from command line or via an url call. After some more research I came up with the following task that will run on a daily basis and publish all blog posts that have been scheduled for the current day:

class PublishBlogpostTask extends BuildTask
{
protected $title = 'Publish Blogposts';
protected $description = 'Automatically publish blogposts.';

/**
* {@inheritDoc}
*/
public function run($request)
{
$lbr = php_sapi_name() === 'cli' ? "\n" : "<br />\n";
$today = strtotime(date('Y-m-d H:i:s'));

$pages = Versioned::get_by_stage('BlogEntry', 'Stage');
foreach ($pages as $page) {
if ($page->isPublished()) {
echo "Skipping page. Page is already published." . $lbr;
continue;
}

$publishOn = strtotime($page->Date);
if (-1 === $publishOn) {
echo "Skipping page. No publishing date found!." . $lbr;
continue;
}

if ($publishOn <= $today) {
echo "Publishing page '{$page->Title}'" . $lbr;
$page->publish('Stage', 'Live');
} else {
echo "Page '{$page->Title}' will not be published" . $lbr;
}
}
}
}

The class above needs to be saved in mysite/code/PublishBlogpostTask.php. To be able to run the task from commandline you need to add a $_FILE_TO_URL_MAPPING entry to your _ss_environment.php file which will tell Silverstripe how to map the local file file path to the url which is used by Silverstripe.

global $_FILE_TO_URL_MAPPING;
$_FILE_TO_URL_MAPPING['/var/www/blog.loc'] = 'http://blog.loc';

Now you are able to run the BuildTask from commandline via:

php framework/cli-script.php dev/tasks/PublishBlogpostTask