Auto update the public date of a page to the publish date

Permalink 2 users found helpful
This is especially useful for websites with blog. Works in concrete5 8.2.1+ (also probably 5.7+).

When you publish a draft, the public date of the page remains set on the time that the draft was created. (Unless you remember to change it in the Composer panel)

Now with this small code, the public date is automatically updated when you publish the draft. It is updated either to the current time or if you decide to schedule the publication, to the scheduled time.

Where to put this code: follow instructions fromhttps://documentation.concrete5.org/developers/application-events/ho...

First you will need these imports:
use \Concrete\Core\Page\Type\Event as PageTypeEvent;
use \Concrete\Core\Page\Collection\Version\Version;


Here is the code:
// Auto update page public date to the publish date
// Source:https://www.concrete5.org/community/forums/usage/auto-update-page-pu...
\Events::addListener('on_page_type_publish', function(PageTypeEvent $event) {
    $page = $event->getPageObject();
    if($page->isPageDraft()) {  // Only update date if page was not already published
        $scheduledVersion = Version::get($page, "SCHEDULED");
        if ($scheduledVersion->cvPublishDate) {     // if publication was scheduled, use the scheduled date
            $date = $scheduledVersion->cvPublishDate;
        } else {
            $date = date('Y-m-d H:i:s');
        }
        $page->update([
            'cDatePublic' => $date
        ]);
    }


Edit: fixed bug where the date would be updated each time a new version was published. It should only update the date at the first publication of the page.