Skip to content

Instantly share code, notes, and snippets.

@santanup789
Created July 28, 2022 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save santanup789/a1745c95d948fea78daad5ce27afb581 to your computer and use it in GitHub Desktop.
Save santanup789/a1745c95d948fea78daad5ce27afb581 to your computer and use it in GitHub Desktop.
Capture post view by capturing IP address using WordPress Function and ACF field [meta field]. Help full for creating any section for Popular Posts.
//Create 2 custom meta field with the names: 'wpb_post_views_count' and 'user_ip'.
<?php
function wpb_set_post_views($postID) {
$user_ip = $_SERVER['REMOTE_ADDR']; //retrieve the current IP address of the visitor
$key = $user_ip . 'x' . $postID; //combine post ID & IP to form unique key
$value = array($user_ip, $postID); // store post ID & IP as separate values (see note)
$visited = get_transient($key); //get transient and store in variable
//check to see if the Post ID/IP ($key) address is currently stored as a transient
if ( false === ( $visited ) ) {
$count_key = 'wpb_post_views_count';
$ipField = 'user_ip';
$count = get_post_meta($postID, $count_key, true);
if ( get_post_meta( $postID, $user_ip, true ) != '' ) {
$ip = json_decode( get_post_meta( $postID, $user_ip, true ), true );
} else {
$ip = array();
}
for ( $i = 0; $i < count( $ip ); $i++ ) {
if ( $ip[$i] == $user_ip )
return false;
}
$ip[ count( $ip ) ] = $user_ip;
$json_ip = json_encode( $ip );
if($count==''){
$count = 1;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '1');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
//delete_post_meta($postID, $ipField);
$olddata = get_field( 'user_ip' );
$newdata = $json_ip;
$margedData = $olddata . ',' . $newdata ;
//update_post_meta($postID, $ipField, $margedData);
update_post_meta($postID, $ipField, $newdata);
if($olddata == '') {
update_post_meta($postID, $ipField, $newdata);
}
else {
$count++;
$newstr = implode(',',array_unique(explode(',', $margedData)));
delete_post_meta($postID, $ipField);
add_post_meta($postID, $ipField, $newstr);
$revisedIPs = get_field( 'user_ip' );
$counter = explode(",",$revisedIPs);
$views = count(explode(",",$revisedIPs));
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, $views);
}
//Above condition will check if any IP are accessing the any post multiple times, so will capture the IP for one time only.
}
}
}
//To keep the count accurate, lets get rid of prefetching
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
function for_single_post() {
if ( is_single() && 'post' == get_post_type() ) {
wpb_set_post_views(get_the_ID());
}
}
add_action( 'wp_footer', 'for_single_post' );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment