Publishing Silverstripe pages via Cron

Publishing Silverstripe pages via Cron

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


Eintrag von Stephan Hochdörfer am 31.03.2014

Tags: Silverstripe, Blog, Publishing, Cron

Diese Webseite verwendet Cookies, um die Bedienfreundlichkeit zu erhöhen. Mit der Nutzung unserer Webseite wird das Einverständnis erklärt, dass wir Cookies verwenden. Weitere Informationen.