Jump to content

Set published date


Martin Muzatko
 Share

Recommended Posts

Hello!

I searched a lot to find various solutions to the problem of setting a custom publish date. Which is a must if you do a redesign of a website and need to write import scripts. Since I can't  re-use the database.

I understand that there is no field to set the dates for created/modified/published manually, but this should be at least possible with the page API.

So I tried to set the published date via API:

$page->of(false);
$page->published = 1486297829;
$page->save();

Which did not work, whenever I ask for $page->published, I get the date back that was first set when publishing the page.

So I researched a little more and found that the Page class stores the published date in $page->settings['settings']; (see Github)

I also tried $page->set('published', 1486297829); but with no success.

Is it possible that this has to be done via SQL? Why? Why can't I use the API? Or do I miss anything?

Thank you a lot in advance!

Link to comment
Share on other sites

I want to set published to an earlier date, which is why the snippet below does not help me unfortunately. Looks like there is no way around manually changing this through SQL :/

$page->of(false);
$page->status = 2049;
$page->save();
$page->status = 1;
$page->save();

I guess there is no other way right now?

I have to say: it is a bit annoying that I'm faced with choosing either a custom publish-date field, when there is an existing one to do the same, or hacking my way around the built-in constraints of published/created/modified.

Thank you a lot already kixe!

Link to comment
Share on other sites

I feel like the "quiet" save option should also work for published. It works for created, but not modified or published.

This SQL will do the trick though:

$sql = "UPDATE `pages` SET `published` = '2015-01-01 12:30:00' WHERE `id` = '2101';";
$database->query($sql);

 

  • Like 2
Link to comment
Share on other sites

  • 6 months later...

Here it is in a hook. Use it with $pages->get(1234)->setPublished($timestamp), where you can get timestamp using strtotime or edit hook to build a date formatted as Y-m-d h:i:s

wire()->addHookMethod('Page::setPublished', function (HookEvent $e) {
    $page = $e->object;
    $timestamp = $e->arguments(0);
    if (!$page->id) return false;
    if (!$timestamp) return false;

    $date = date('Y-m-d h:i:s', $timestamp);

    $query = $e->database->prepare("UPDATE pages SET published=:pub_date WHERE id=:page_id");

    $e->return = $query->execute([
        ':pub_date' => $date,
        ':page_id' => $page->id
    ]);
});

 

  • Like 4
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...