wordpress 限制同个IP用户注册数量

在WordPress中,可以通过插件或者直接修改代码来限制同一IP地址的用户注册数量。以下是通过直接修改代码来实现的方法:

打开你的WordPress主题的functions.php文件,或者你创建的任何一个插件文件。

将以下代码添加到该文件中:

方法一:wordpress 限制同个IP用户注册数量

// wordpress 限制同个IP用户注册数量
function limit_registration_by_ip($allow, $user_login, $errors) {
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
 
    $args = array(
        'number' => 5, // 你想要限制的注册数量
        'ip' => $ip,
        'role' => '',
        'meta_key' => '',
        'meta_value' => ''
    );
 
    $users = get_users($args);
 
    if (count($users) >= $args['number']) {
        $allow = false;
        $errors->add('ip_limit_reached', __('Sorry, the maximum number of users from your IP address has been reached. Please try again later.'));
    }
 
    return $allow;
}
 
add_filter('registration_errors', 'limit_registration_by_ip', 10, 3);

方法二:wordpress 限制同个IP每天用户注册数量

// wordpress 限制同个IP每天用户注册数量
function limit_registration_by_ip() {
    // 获取当前时间戳
    $current_time = current_time('timestamp');
    // 获取用户注册限制的选项
    $daily_limit = get_option('limit_registration_by_ip_daily');
 
    // 如果选项不存在或者当前时间超过了限制的结束时间,重置计数器
    if (!$daily_limit || $current_time > strtotime($daily_limit['expire'])) {
        $daily_limit = array(
            'count' => 0,
            'expire' => date('Y-m-d H:i:s', $current_time + 86400) // 设置明天的这个时间为重置时间
        );
        update_option('limit_registration_by_ip_daily', $daily_limit);
    }
 
    // 获取IP地址
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $ip_limit = get_option("limit_registration_by_ip_{$ip_address}");
 
    // 如果IP限制选项不存在,创建它
    if (!$ip_limit) {
        $ip_limit = array(
            'count' => 0,
            'expire' => $daily_limit['expire']
        );
        update_option("limit_registration_by_ip_{$ip_address}", $ip_limit);
    }
 
    // 检查今天的注册次数是否已经超过限制
    if ($ip_limit['count'] >= $daily_limit['count']) {
        // 触发错误
        return new WP_Error('ip_registration_limit_exceeded', 'You have reached the maximum number of signups allowed from your IP address today. Please try again tomorrow.');
    }
 
    // 增加计数器
    $ip_limit['count']++;
    update_option("limit_registration_by_ip_{$ip_address}", $ip_limit);
}
 
add_action('registration_errors', 'limit_registration_by_ip');