我正在尝试制作一个用于wordpress访问者计数器和限制访问者计数的插件。我写了这段代码,但是每次刷新页面时,计数器变量都会增加4倍或5倍。基本上,插件是免费访问的,用户应该登录免费访问网站后才能免费访问。请检查代码。
<?php
$count=0;
function ip_get(){
if(!empty($_SERVER['HTTP_CLIENT_IP'])){
//ip from share internet
$new_ip = $_SERVER['HTTP_CLIENT_IP'];
}elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
//ip pass from proxy
$new_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$new_ip = $_SERVER['REMOTE_ADDR'];
}
global $wpdb;
$table_name=$wpdb->prefix.'wbs_user_ips';
$results = $wpdb->get_results( "SELECT * FROM $table_name"); // Query to fetch data from database table and storing in $results
if(empty($results)){
$wpdb->insert($table_name,
array(
'user_ip'=>$new_ip,
'user_count'=>'1',
'user_status'=>'0',
)
);
}
if(!empty($results)) // Checking if $results have some values or not
{
$count=0;
foreach($results as $row){
$ip= $row->user_ip;
$count=$row->user_count;
}
if($ip==$new_ip){
echo $count++;
$wpdb->query($wpdb->prepare("UPDATE $table_name
SET user_count=".$count."
WHERE user_ip = %s",$ip));
}
}
}
?>
答案 0 :(得分:0)
我认为您的foreach循环中有错误。 并且请确保您使用正确的hook
<?php
$count=0;
function ip_get(){
if(!empty($_SERVER['HTTP_CLIENT_IP'])){
//ip from share internet
$new_ip = $_SERVER['HTTP_CLIENT_IP'];
}elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
//ip pass from proxy
$new_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$new_ip = $_SERVER['REMOTE_ADDR'];
}
global $wpdb;
$table_name=$wpdb->prefix.'wbs_user_ips';
$results = $wpdb->get_results( "SELECT * FROM $table_name"); // Query to fetch data from database table and storing in $results
if(empty($results)){
$wpdb->insert($table_name,
array(
'user_ip'=>$new_ip,
'user_count'=>'1',
'user_status'=>'0',
)
);
}
if(!empty($results)) // Checking if $results have some values or not
{
$count=0;
foreach($results as $row){
$ip= $row->user_ip;
$count=$row->user_count;
if($ip==$new_ip){
echo $count++;
$wpdb->query($wpdb->prepare("UPDATE $table_name
SET user_count=".$count."
WHERE user_ip = %s",$ip));
}
}
}
}
?>