I have this code for count the views of page :
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
function PostViews($postID) {
$key = 'post_views_count';
$count = get_post_meta($postID, $key, true);
if($count==''){
$count = 1;
delete_post_meta($postID, $key);
add_post_meta($postID, $key, '1');
return $count;
}else{
$count++;
update_post_meta($postID, $key, $count);
return $count;
}
}
the problem is when i visit the page every time add one view , how to ignore the same IP from added again ?
Save the user's IP address into an array. Save the JSON
encoded version of the array into the database then decode and loop through it to match the IP addresses.
function update_post_views( $post_id ) {
// The user's IP address
$user_ip = $_SERVER['REMOTE_ADDR'];
$views_key = 'post_views_count'; // The views post meta key
$ip_key = 'post_views_ip'; // The IP Address post meta key
// The current post views count
$count = get_post_meta( $post_id, $views_key, true );
// Array of IP addresses that have already visited the post.
if ( get_post_meta( $post_id, $ip_key, true ) != '' ) {
$ip = json_decode( get_post_meta( $post_id, $ip_key, true ), true );
} else {
$ip = array();
}
/*
The following checks if the user's IP already exists
*/
for ( $i = 0; $i < count( $ip ); $i++ ) {
if ( $ip[$i] == $user_ip )
return false;
}
/*
If the script has gotten this far, it means that
the user's IP address isn't in the database.
*/
// Update and encode the $ip array into a JSON string
$ip[ count( $ip ) ] = $user_ip;
$json_ip = json_encode( $ip );
// Update the post's metadata
update_post_meta( $post_id, $views_key, $count++ ); // Update the count
update_post_meta( $post_id, $ip_key, $json_ip ); // Update the user IP JSON obect
}
Hope that helps!