Jump to content

Auto incrementing page names with trailing number (year)


iank
 Share

Recommended Posts

Scenario

I'm importing a whole number of pages via the API which will have titles such as "A Page Title | October 2018" and "Another Page Title | November 2018" and so on.

However, there are some duplicates (the titles come from repeaters in another PW installation;  these may well have the same title, but a different photo, for example).

So, if I'm importing several pages with the same name, let's say:

  • "A Page Title | October 2018"
  • "A Page Title | October 2018" 
  • "A Page Title | October 2018" 

PW knows how to increment page names when they would be duplicated.  I want these to create page names like the following:

  • a-page-title-october-2018
  • a-page-title-october-2018-1
  • a-page-title-october-2018-2

but instead, the generated page names are:

  • a-page-title-october-2018
  • a-page-title-october-2019  <=   
  • a-page-title-october-2020  <= not what I wanted!!

The same behaviour occurs in the PW admin too.  Does anybody have a suggestion how to override this situation?

Thanks,

Ian.

 

Link to comment
Share on other sites

I took the liberty of opening a GitHub issue for this problem: https://github.com/processwire/processwire-issues/issues/1192

As a workaround for now you could use this hook in /site/ready.php:

$pages->addHookBefore('added', function(HookEvent $event) {
	/** @var Page $page */
	$page = $event->arguments(0);
	/** @var Pages $pages */
	$pages = $event->object;
	// Only for a particular template
	if($page->template != 'your_template') return;
	// Check if there is a name clash with an existing sibling page
	$default_name = $this->wire('sanitizer')->pageName($page->title, true);
	if($pages->count("parent=$page->parent, id!=$page->id, name=$default_name, include=all")) {
		// Manually create a proposed name
		$name = $default_name . '-1';
		// Auto-adjust the name when needed
		$name = $pages->names()->uniquePageName($name, $page);
		// Set the name
		$page->setAndSave('name', $name);
	}
});

 

  • 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

  • Recently Browsing   0 members

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