WordPress creating plugin for most viewed posts problem?

I just want to create plugin that will when visitor(user,visitor,…) visit some post,remember what post,and to increment counter of that post,I wrote this code,but sometimes,counter is incremented,even post isn’t viewed,or post with other Id is added to a table.Can someone help me with this,please.I know that there are plugins for this that I’m trying to do,but still want to write this plugin.

function IncrementPostCount($the_content) {
    global $post;
    global $wpdb;

    if(($post->post_status == 'publish') && (int)$post->ID) {

        if(is_single()) { // just for single post - not for page
            $postID = (int)$post->ID;

            $postTitle = urlencode($post->post_title);
            $postLink = urlencode(get_permalink($post->ID));

            $oneRow = $wpdb->get_row("SELECT * FROM wp_postovi WHERE postAjDi='$postID'");

            if(empty ($oneRow)) {
                $postCounter = 1;
                $data_array = array(
                   'readnTimes' => $postCounter, 
                   'linkPost'=>$postLink, 
                   'TitlePost'=>$postTitle,
                   'postAjDi'=>$postID);
                $wpdb->insert('wp_najcitaniji_postovi', $data_array);                
            }
            else {
                $postCounter = intval($oneRow->readnTimes) + 1;
                $data_array = array('readnTimes' => $postCounter);
                $where_array = array('postAjDi'=>intval($oneRow->postAjDi));
                $wpdb->update('wp_postovi',$data_array,$where_array);
            }

            return $the_content;
        }
        return $the_content;
    }
}
add_filter('the_content','IncrementPostCount');

Sorry on my bad english,tnx in advance.

Related posts

Leave a Reply

1 comment

  1. Here’s how to do that with the postmeta table.

    function IncrementPostCount(){
      if(is_single()){
        global $wp_query;
        $count = get_post_meta( $wp_query->post->ID, 'readnTimes', true );
        $count = empty($count) ? 1 : $count + 1;
        add_post_meta($wp_query->post->ID, 'readnTimes', $count, true) or update_post_meta($wp_query->post->ID, 'readnTimes', $count);
      }
    }
    add_action( 'template_redirect', 'IncrementPostCount' );
    

    Also, it’s better to hook it in earlier. That way, the count is only incremented once per page load (the_content can be fired multiple times per page, even on a single page. template_redirect only fires once per request). Also, if you store the data at template_redirect, you can use the updated view count in the template, giving your visitors an even more accurate view count.

    And you don’t need to worry about database tables, custom SQL, or any of that.