• Hello fellow programmers,

    I’m having trouble coding a reliable post views counter.
    Basically whenever a post hit occurs I’m adding meta to the author with two separate keys (weekly and total views).

    There are times however that there are more weekly than total views, which means that some hits are not calculated at all whereas both functions look the same.

    The code is fired from within a footer via jQuery.post function that posts the respective post / author values to the backend.

    The code adding the meta looks like that:

    // $post_meta is meta read before
    /*----------------------------------------------*/
    if ( !empty( $post_meta ) ) {
                            // ip addresses are stored as well
    			if (  !in_array( $ip, $post_meta ) ) {
    				echo $post_id, $aid;
    				add_post_meta( $post_id, self::$ip_address, $ip );
    				self::add_total_views( $aid );
    				self::add_weekly_views( $aid );
    			}
    		} else {
    			add_post_meta( $post_id, self::$ip_address, $ip );
    			self::add_total_views( $aid );
    			self::add_weekly_views( $aid );
    		}
    
    /*----------------------------------------------*/
    static function add_weekly_views($aid) {
    		$weekly_views = get_user_meta( $aid, self::$weekly_key, true );
    		$weekly_views = !empty( $weekly_views ) ? intval( $weekly_views ) : 1;
    		$weekly_views = $weekly_views + 1;
    		update_user_meta( $aid, self::$weekly_key, $weekly_views );
    	}

    Could you please point me out what should I be doing wrong?
    Perhapos there’s no way to write I 100% reliable counter, due to delay between php and mysql server. So I’d have to store both counters as one meta key.

    Any clues?

    Thank you in advance,
    Rafal Gicgier

  • The topic ‘Creating reliable post views per user counter’ is closed to new replies.