Skip to content

Instantly share code, notes, and snippets.

@smileBeda
Created July 27, 2023 03:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smileBeda/e439854fba76302c72b11318dc60b591 to your computer and use it in GitHub Desktop.
Save smileBeda/e439854fba76302c72b11318dc60b591 to your computer and use it in GitHub Desktop.
Fix the WordPress Delete Users functionality
/**
* User AJAX Search
*
* Used for the Select2 in the User Delete admin area
*
* @since Added 2023-07-26 11:49
* @author Beda Schmid <beda@tukutoi.com>
* @return void
*/
public function ajax_get_users() {
$search = isset( $_GET['search'] ) ? $_GET['search'] : '';
$users = get_users(
array(
'search' => esc_attr( $search ),
'search_columns' => array(
'user_login',
'user_nicename',
),
)
);
$users_array = array();
foreach ( $users as $user ) {
$users_array[] = array('id' => $user->ID, 'text' => $user->user_login);
}
echo wp_json_encode( $users_array );
wp_die();
}
/**
* On deleting a user
*
* When deleting an user, also re-assign comments, if any.
*
* @since Added 2023-07-27 09:26
* @author Beda Schmid <beda@tukutoi.com>
* @param int $id The user ID to be deleted.
* @param int $reassign The user ID to be re-assigned.
* @return void
*/
public function on_delete_user( $id, $reassign ){
if ( null === $reassign ) {
return;
}
$comment_ids = get_comments(
array(
'user_id' => $id,
'fields' => 'ids',
)
);
if ( empty( $comment_ids ) ) {
return;
}
foreach ( $comment_ids as $comment_id ) {
$userassign = get_user_by( 'id', $reassign );
if ( ! is_a( $userassign, 'WP_User' ) ) {
return;
}
wp_update_comment(
array(
'comment_ID' => $comment_id,
'user_id' => $reassign,
'comment_author' => $userassign->data->user_nicename,
'comment_author_email' => $userassign->user_email,
),
false
);
}
}
/**
* Check if user has more content
*
* If a user is deleted, WP only checks if there are posts. We also check if there are comments.
*
* @since Added 2023-07-27 09:25
* @author Beda Schmid <beda@tukutoi.com>
* @param bool $users_have_additional_content If the user has additional content or not.
* @param array $user_ids Array of users to be deleted.
* @return bool $users_have_additional_content
*/
public function to_delete_users_content( $users_have_additional_content, $user_ids ) {
foreach ( $user_ids as $user_id ) {
$comments = get_comments(
array(
'user_id' => $user_id,
'count' => true,
)
);
if ( 0 < $comments ) {
$users_have_additional_content = true;
} else {
$users_have_additional_content = false;
}
return $users_have_additional_content;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment