Score:2

How can I programmatically delete a user without deleting their content?

us flag

I want to delete a user with this code:

$account = User::load(19920);
$account->delete();

How can I do that without also deleting the user's content?

I've been reviewing _user_cancel() hooks, but they all seem to be about doing things in the admin UI.

This hook works the way I expect it to and removes the user_cancel_delete radio button option from the admin UI.

/**
 * Implements hook_user_cancel_methods_alter().
 */
function my_user_module_user_cancel_methods_alter(&$methods) {
  // Remove Delete the account and its content method.
  unset($methods['user_cancel_delete']);
}

but I want to not delete content when $account->delete() is called in my update hook.

Score:4
cn flag

Yes, you can use the user_cancel process to prevent content being deleted. As you found out it doesn't help to remove the options from UI. Programmatically you need to call the function directly, specifying the method user_cancel_reassign to replace the author with anonymous before deleting the user:

user_cancel([], $uid, 'user_cancel_reassign');
$account = User::load($uid);
$account->delete();

Caveat: This doesn't work for more than 10 pieces of content. Then you need to run this as a batch, which also would delete the user as final step of the batch process. See user deletion : user_cancel_reassign not working when user has more than 10 associated contents

us flag
Thanks @4k4. `user_cancel([], $uid, 'user_cancel_reassign');` was the thing I was missing. I'm sure it's been around forever in Drupal. lol. I'll also have a look at when working with more than 10 pieces of content, which I'm sure will come up.
4uk4 avatar
cn flag
Yes, this looks like ancient Drupal code. It might be more future-proof to query the nodes and change the author to anonymous yourself.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.