帖子视图按IP计算

时间:2013-11-17 20:43:55

标签: php wordpress ip views

我有这个代码来计算页面的视图:

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;
}
}

问题是当我每次访问页面时添加一个视图,如何忽略同一IP再次添加?

1 个答案:

答案 0 :(得分:1)

将用户的IP地址保存到阵列中。将数组的JSON编码版本保存到数据库中,然后解码并遍历它以匹配IP地址。

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

}

希望有所帮助!