WordPress搜索怎么添加人机验证_WP搜索添加人机验证教程

WordPress教程 pcbiji 3364浏览 0评论

想必 WordPress 站长都用过它的搜索功能,如果网站数据很多,用起来就会非常占用系统资源,如果被别有用心的人利用了,就可以导致网站被攻击,无法访问的情况出现。基于这种情况,我们可以给 WordPress 的搜索添加人机验证,今天电脑笔记网就来给大家分享 WP 搜索添加人机验证教程

WordPress 搜索怎么添加人机验证

WordPress 搜索怎么添加人机验证

我们只需要增加一个简单的人机验证就可以过滤掉恶意请求,在用户第一次搜索时弹出一个人机验证,确保是真实的搜索就可以了,只需要将下列代码添加到当前主题的 functions.php中。

function esc_search_captcha( $query, $error = true ) {
	if ( is_search() && !is_admin() ) {
		if ( ! isset( $_COOKIE['esc_search_captcha'] ) ) {
			$query->is_search = false;
			$query->query_vars['s'] = false;
			$query->query['s'] = false;
 
			if ( $error == true ){
				//$query->is_404 = true;
				if ( isset( $_POST['result'] ) ) {
					if ( $_POST['result'] == $_COOKIE['result'] ) {
						$_COOKIE['esc_search_captcha'] = 1;
						setcookie('esc_search_captcha',1,0,'/');
						echo '<script>location.reload();</script>';
					}
				}
 
				$num1 = rand(1,50);
				$num2 = rand(1,50);
				$result = $num1+$num2;
				$_COOKIE['result'] = $result;
				setcookie('result',urldecode($result),0,'/');
				?>
 
				<html>
				<head>
				<meta charset="UTF-8">
				<title>人机验证</title>
				<style>
				body{color: #333;text-align: center;font-size: 16px;}
				.erphp-search-captcha{margin: 50px auto 15px;max-width: 250px;width: 100%;padding: 40px 20px;border: 1px solid #ddd;text-align: center;border-radius: 5px;}
				.erphp-search-captcha form{margin: 0}
				.erphp-search-captcha input{border: none;border-bottom: 1px solid #666;width: 50px;text-align: center;font-size: 16px;}
				.erphp-search-captcha input:focus{outline: none;}
				.erphp-search-captcha button{border: none;background: transparent;color: #ff5f33;cursor: pointer;}
				.erphp-search-captcha button:focus{outline: none;}
				a{color: #000;font-size: 12px;}
				</style>
				</head>
				<body>
				<div class="erphp-search-captcha">
				<form action="" method="post"><?php echo $num1;?> + <?php echo $num2;?> = <input type="text" name="result" required /> <button type="submit">验证</button></form>
				</div>
				<a href="<?php echo home_url();?>">返回首页</a>
				</body>
				</html>
				<?php
				exit;
			}
		}
	}
}
add_action( 'parse_query', 'esc_search_captcha' );

以上这些内容就是 WP 搜索添加人机验证教程,如果你不使用插件来进行人机验证,上面的代码就是最好的选择,有需要的站长朋友可以来试试这段代码了,需要提醒大家的是,这段代码的功能只会验证一次,除非你清空了浏览器的 cookie 信息才会再次验证。

转载请注明:电脑笔记网 » WordPress搜索怎么添加人机验证_WP搜索添加人机验证教程

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址