• Hello! Please help me understand, trying to write simple counter views plugin, but i have small problem.
    Why is counter “views” no increase by one?

    add_action('wp_head', 'nopvys_views');
    function nopvys_views() {
    	global $post;
    	if(is_int($post))
    	{
    	$post = get_post($post);
    	}
    	if(!wp_is_post_revision($post)) {
    		if(is_single() || is_page()) {
    			$id = intval($post->ID);
    			global $wpdb;
    			$ip=$_SERVER['REMOTE_ADDR'];
    			global $wpdb;
    			$query=$wpdb->get_row($wpdb->prepare("select * from ".$wpdb->prefix."views_date where post_id=$id AND ip_address='$ip' AND date(view_date)=DATE(NOW())", null));
    			if(!$query)
    			{
                $wpdb->insert($wpdb->prefix."views_date",
    			array(
    			'post_id' =>$id,
    			'ip_address'=>$ip,
    		    'view_date'=> date( 'Y-m-d H:i:s')
    		          ),
    				  array('%s', '%s', '%s'));
                $thepost = $wpdb->get_row( $wpdb->prepare("select * from ".$wpdb->prefix."views_count where post_id=$id AND hosts='$hs' AND views='$vs'",null));
    			$hs=$thepost->hosts;
    			$vs=$thepost->views;
                if(!$thepost)
                {
    			   	$wpdb->insert($wpdb->prefix."views_count",
                    array(
    				'post_id' =>$id,
    		        'hosts'=> 1,
    				'views'=> 1
    		             ),
    					 array('%s', '%d', '%d'));
                }
    			$current_ip = $wpdb->get_var("select ip_id from ".$wpdb->prefix."views_date where ip_address='$ip'");
    			if($current_ip == 1)
                {
    				$wpdb->update($wpdb->prefix."views_count",
                    array( 'views' => 'views'+1),
                    array( 'post_id' => $id ),
                    array( '%d' ),
                    array( '%d' )
                         );
                }
    			}
    		}
    	}
    }

Viewing 1 replies (of 1 total)
  • Hello,

    I think the problem is the way you treat $post.
    Your function checks to see if it’s an int. However, it is a WP_Post object, so you might not get much further than that.

    You probably should:
    1. Check to see if $post is set.
    2. If it is, you can skip the get_post stuff — since $post already is the post in question.

    Give it a shot. Hope this helps — I haven’t had my morning coffee yet!

    global $post;
    	if(is_int($post))
    	{
    	$post = get_post($post);
    	}
Viewing 1 replies (of 1 total)
  • The topic ‘update record in database’ is closed to new replies.