Jump to content

Exclude "page copying" from addHookAfter("saved")


chumneypwire
 Share

Recommended Posts

I was curious, is it possible to exclude the addHookAfter("saved") from running when copying pages. I have a function (currently running in ready.php) that runs on page save for certain templates.

$pages->addHookAfter('saved', function($event) {
	$page = $event->arguments[0];
	if($page->template->name == 'dev'
....

The function basically just adds the page title to a csv using fwrite if the name does not exist yet. This is functioning great, however, it also runs when copying the pages which produce some unwanted results, ie:

dev-page

dev-page-1 (the title of the copied page before I have a chance to rename the title and name).

I end up with a bunch of *-# pages, as well as the new page names/titles. Is it possible to somehow get around the copying also running the function?

Link to comment
Share on other sites

2 hours ago, chumneypwire said:

the title of the copied page before I have a chance to rename the title and name

I think ProcessPageClone should give the user an opportunity to specify a title and name for the page before the clone is done, as is the case for cloning pages with children. I opened a request for this.

But in the meantime you could check to see if a sibling page exists with the same name as the cloned page excluding the "-1" suffix.

$base_name = rtrim($page->name, '-1');
if($page->siblings("name=$base_name", false)->count()) return;

Edit: or maybe a better approach is not to write to your CSV for unpublished pages, as cloned pages are unpublished at first.

  • Like 2
Link to comment
Share on other sites

Thanks Robin, I was going to implement a check for unpublished, but I think I am missing something here:

if($page->status != $page->isUnpublished()) {
	fwrite($myfile, $txt);
	fclose($myfile);
}

I did also note that it is writing to the file as well when the page is added to the trash. Is there a way to include this in the if as well?

Link to comment
Share on other sites

A couple of different ways...

$pages->addHookAfter('saved', function(HookEvent $event) {
    $page = $event->arguments(0);
    if($page->hasStatus('unpublished') || $page->hasStatus('trash')) return;
    // Your code...
});
$pages->addHookAfter('saved', function(HookEvent $event) {
    $page = $event->arguments(0);
    if($page->isUnpublished() || $page->isTrash()) return;
    // Your code...
});

 

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