How to Delete Unauthorized Users in WordPress

Managing user access is crucial for maintaining the security and integrity of your WordPress site. If you find unauthorized users or accounts that shouldn’t have access, you can easily remove them.

That Code Use to any attack to protect and that code site hacking in hackers chance is very low.

require_once 'wp-load.php'; 

if (!function_exists('wp_delete_user')) {
        require_once(ABSPATH . 'wp-admin/includes/user.php');
    }

    $users = get_users();   // Get all users

    // Loop through each user and check their post count
    foreach ($users as $user) {
        $user_posts = count_user_posts($user->ID);

        // If user has zero posts, delete them
        if ($user_posts == 0) {
            wp_delete_user($user->ID);
        }
    }

How To Use

  • Loading WordPress Functions:
    • The script begins by loading the WordPress environment with require_once 'wp-load.php';. This ensures that all necessary WordPress functions are available for use.
    • It checks if the wp_delete_user function exists, which is essential for deleting users. If it doesn’t, it includes the required file from the admin directory.
  • Fetching Users:
    • The get_users() function retrieves all users from the WordPress database.
  • Counting User Posts:
    • The script iterates through each user using a foreach loop.
    • For each user, it counts their posts with count_user_posts($user->ID).
  • Deleting Inactive Users:
    • If a user has zero posts ($user_posts == 0), the script calls wp_delete_user($user->ID) to delete the user from the database.

Usage

  • Customization: Adjust the path in require_once 'wp-load.php'; as necessary based on your WordPress installation.
  • Execution: This script can be run in a custom plugin or a theme’s functions file. However, ensure that you have a backup of your database before executing any deletion script.
See also :  convert number to words in php - how to convert number to words in php?

Important Considerations

  • Backup: Always back up your database before running scripts that modify or delete data.
  • Permissions: Make sure the user account you are using to run the script has the necessary permissions to delete users.

Leave a Comment