Jump to content

change default url slug creation


benbyf
 Share

Recommended Posts

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.

Link to comment
Share on other sites

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
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

  • Recently Browsing   0 members

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