Jump to content

Recommended Posts

Posted

By default a page in PW has a slug created by the pages title or name converted to lower and dashed including the hierachy of the page and parents e.g. site.com/parent-slug/new-page-slug

Is there a module or some hook I can use to change this behavior? I'm looking to randomly generate the url slug to hide the title contents.

Posted

Yes, that's quite easy and something that I need all the time:

<?php
// site/ready.php
$wire->addHookAfter("Pages::saveReady", function(HookEvent $event) {
  $page = $event->arguments(0);
  
  // only rename pages with template 'yourtemplate'
  if($page->template != 'yourtemplate') return;
  
  // only execute the hook when the page is created
  // otherwise the page name would be regenerated on every save
  if($page->id) return;
  
  // create a unique random pagename
  // see the methods docs for all available options
  $page->name = $event->wire->pages->names->uniqueRandomPageName();
});

I recommend to add notes to the backend to make it obvious what's going on and where:

<?php
// site/ready.php
$wire->addHookAfter("ProcessPageEdit::buildForm", function(HookEvent $event) {
  $form = $event->return;
  $field = $form->get('_pw_page_name');
  $field->collapsed = Inputfield::collapsedNoLocked;
  $field->notes = "Random page name is set via hook in ready.php";
});

 

  • Like 2
  • 2 years later...
Posted (edited)

This is very helpful!

At the moment, I am trying to alternate this to add the date to the pagename (url).

Instead of creating a unique random pagename, I put this line:

$page->name = date("Y-m-d-") . $page->name;

I wanted to add this by preventing the error when creating a page with a name that is already given.
 

Edited by mjut

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
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...