Set Title & Slug to current time?

Hi folks,

I thought this would be a simple, but it appears not. What I would like to do is have the title and slug to be automatically generated when I create a “note” page within the panel.

In my ‘note’ blueprint I added the following:

create:
  title: <?php echo date('Ymd-Hi'); ?>
  slug: <?php echo date('Ymd-Hi'); ?>

But it seems that kirby won’t parse the php. So I tried doing it with a hook too, so I change the “create” options to something simple, like “note”:

create:
  title: note
  slug: note

Then have a hook to change the title/slug after the page is created:

'hooks' => [
        'page.create:after' => function ($newPage) {
            // Check if the created page is of the template 'note'
            if ($newPage->intendedTemplate() === 'note') {
                // Get the current date/time in the desired format
                $dateTime = date('Ymd-Hi');
                
                // Update the title and slug of the page to match the current date/time
                $newPage->update([
                    'title' => $dateTime,
                    'slug' => $dateTime
                ]);
            }
        }
    ]

But this doesn’t work either. The title/slug just remain as “note”. Clearly I’m being an idiot, but I can’t work this seemingly simple thing out.

Thanks!

I also tried using this:

create:
  title: '{{ page.published.toDate("Ymd-Hi") }}' 
  slug: '{{ page.published.toDate("Ymd-Hi") }}'

But it didn’t work either. I assume that’s because the page was still being created, so the published field wasn’t yet populated. So I tried this:

create:
  title: '{{ now.toDate("Ymd-Hi") }}'
  slug: '{{ now.toDate("Ymd-Hi") }}'

That was another fail, lol.

Hey Kev!

I followed this section in the docs and got it working.

Create a new plugin:
site/plugins/date-to-slug/index.php

Add this code to index.php:

<?php

Kirby::plugin('getkirby/date-to-slug', [
  'siteMethods' => [
    'time' => function() {
      return date('Ymd-Hi');
    }
  ]
]);

In your note blueprint, update the fields:

create:
  title: "{{ site.time }}"
  slug: "{{ site.time }}"

This is the result after creating a new note page:

The other option would be to include the date field (published) in the create dialog.

Huzzah! That worked, thanks Luke.

I changed the plugin slightly so it’s this:

<?php

Kirby::plugin('getkirby/date-to-slug', [
  'siteMethods' => [
    'time' => function() {
      return date('Ymd-Hi');
    },
    'pretty-time' => function() {
        return date('j F Y \a\t H:i');
      }
  ]
]);

Then added the following to my blueprint:

create:
  title: "{{ site.pretty-time }}"
  slug: "{{ site.time }}"

This way the slug is something like 20240522-2108 but the title is 22 May 2024 at 21:08.

Thanks again.

1 Like