Wordpress page views hack

I created this pretty quick, and it is by far, not the prettiest thing out there. This uses an extra table in the MySQL table to keep track of pages that get viewed and how many times they are viewed. Here is what I did:

Step 1 – Create a new table!
Go to your MySQL database and create a table called “wp_counter” with 2 fields: Post_Id and Count. Both are Int with length 10. Here is the SQL code you can copy and paste to make it a bit shorter:
CREATE TABLE `wp_counter` (`Post_Id` INT( 10 ) NOT NULL , `Count` INT( 10 ) NOT NULL)

Step 2 – Editing post-template.php
This is the file that is used to display your posts (not the snippets on your front page, but full out posts). It is located in the “wp-includes” directory.
Open post-template.php for editing.
Search for a function called “the_content()“. It typically starts on line 165 should look like this:

165
166
167
168
169
170
function the_content($more_link_text = null, $stripteaser = 0, $more_file = '') {
	$content = get_the_content($more_link_text, $stripteaser, $more_file);
	$content = apply_filters('the_content', $content);
	$content = str_replace(']]>', ']]>', $content);
	echo $content;
}

So what we want to do is make it so that every time it shows the content, it will update the count and display it to the user. So we are going to change that function to look like this:

165
166
167
168
169
170
171
172
function the_content($more_link_text = null, $stripteaser = 0, $more_file = '') {
	$content = get_the_content($more_link_text, $stripteaser, $more_file);
	$content = apply_filters('the_content', $content);
	$content = str_replace(']]>', ']]>', $content);
	echo $content;
	update_count();
	echo"<small><i>Views: ".get_content_views()."</i></small>";
}

And immediately following that, we are going to add a couple functions:

173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
function update_count(){
	global $wpdb, $id;
	if($wpdb->query($wpdb->prepare("SELECT * FROM wp_counter WHERE Post_Id='$id'"))==0)
		$wpdb->insert("wp_counter",array('Post_Id'=>$id,'Count'=>1),array('%d','%d'));
	else {
		$row=$wpdb->get_row($wpdb->prepare("SELECT * FROM wp_counter WHERE Post_Id='$id'"),ARRAY_A);
		$count=$row['Count']+1;
		$wpdb->update('wp_counter',array('Count'=>$count),array('Post_Id'=>$id),array('%d'),array('%d'));
	}
}
function content_views(){
	global $wpdb, $id;
	$row=$wpdb->get_row($wpdb->prepare("SELECT * FROM wp_counter WHERE Post_Id='$id'"),ARRAY_A);
	echo $row['Count'];
}

That’s it! So your finalized post-template.php will look like this:

function the_content($more_link_text = null, $stripteaser = 0, $more_file = '') {
	$content = get_the_content($more_link_text, $stripteaser, $more_file);
	$content = apply_filters('the_content', $content);
	$content = str_replace(']]>', ']]&gt;', $content);
	echo $content;
	update_count();
	echo"<small><i>Views: ".get_content_views()."</i></small>";
}
function update_count(){
	global $wpdb, $id;
	if($wpdb->query($wpdb->prepare("SELECT * FROM wp_counter WHERE Post_Id='$id'"))==0)
		$wpdb->insert("wp_counter",array('Post_Id'=>$id,'Count'=>1),array('%d','%d'));
	else {
		$row=$wpdb->get_row($wpdb->prepare("SELECT * FROM wp_counter WHERE Post_Id='$id'"),ARRAY_A);
		$count=$row['Count']+1;
		$wpdb->update('wp_counter',array('Count'=>$count),array('Post_Id'=>$id),array('%d'),array('%d'));
	}
}
function content_views(){
	global $wpdb, $id;
	$row=$wpdb->get_row($wpdb->prepare("SELECT * FROM wp_counter WHERE Post_Id='$id'"),ARRAY_A);
	echo $row['Count'];
}
function get_content_views(){
	global $wpdb, $id;
	$row=$wpdb->get_row($wpdb->prepare("SELECT * FROM wp_counter WHERE Post_Id='$id'"),ARRAY_A);
	return $row['Count'];
}

Now every time someone visits the page, they will see how many other people have viewed that page!

Views: 2067
July 28th, 2009 Add a comment
Home > Tutorials > Wordpress page views hack
Comments (10) Trackback Leave a comment
  1. pyr0t3chnician
    July 28th, 2009 at 15:07 | #1

    Because of the way it is written, viewing archives or topics will result in page views because they used the function “the_content()”. The fix this, I removed the lines I added to that function:

    update_count();
    echo"Views: ".get_content_views()."";

    Then I went into the theme itself on the single post template and page template. Where it says, “the_content();”, I just changed it to look like this:

    the_content();update_count();echo"Views: ".get_content_views()."";

    Now only people who visit a single post or page will have their views counted.

  2. pyr0t3chnician
    July 28th, 2009 at 15:10 | #2

    Also just wanted to point out the widget on the side that uses this database to display the data. I may post the entire widget, complete with table creation and function creation. We will see.

  3. August 30th, 2009 at 12:41 | #3

    How do you pick the words so skillfully

  4. October 1st, 2009 at 01:17 | #4

    I don’t know If I said it already but …I’m so glad I found this site…Keep up the good work I read a lot of blogs on a daily basis and for the most part, people lack substance but, I just wanted to make a quick comment to say GREAT blog. Thanks, :)

    A definite great read..Jim Bean

  5. October 6th, 2009 at 12:03 | #5

    Generally I do not post on blogs, but I would like to say that this post really forced me to do so, Excellent post! :)

  6. Josh
    November 13th, 2009 at 07:30 | #6

    Hmm… I tried adding those two additional functions to my functions.php file… but it’s not working.

    Here’s what I’ve added to my functions.php file:

    // Adding total pageviews to each post
    function update_count(){
    	global $wpdb, $id;
     
       $table_name = $wpdb-&gt;prefix . "wpcount";
       if($wpdb-&gt;get_var("show tables like '$table_name'") != $table_name) {
          $row1name = 'post_id';
    	  $row2name = 'count';
     
          $sql = 'CREATE TABLE '.$table_name.' ('.$row1name.' INT( 10 ) NOT NULL , '.$row2name.' INT( 10 ) NOT NULL) ';
     
          require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
          dbDelta($sql);
    	}
     
    	if($wpdb-&gt;query($wpdb-&gt;prepare("SELECT * FROM ".$table_name." WHERE post_id='$id'"))==0)
    		$wpdb-&gt;insert($table_name,array('post_id'=&gt;$id,'count'=&gt;1),array('%d','%d'));
    	else {
    		$row=$wpdb-&gt;get_row($wpdb-&gt;prepare("SELECT * FROM ".$table_name." WHERE post_id='$id'"),ARRAY_A);
    		$count=$row['count']+1;
    		$wpdb-&gt;update($table_name,array('count'=&gt;$count),array('post_id'=&gt;$id),array('%d'),array('%d'));
    	}
    }
    function content_views(){
    	global $wpdb, $id;
    	$row=$wpdb-&gt;get_row($wpdb-&gt;prepare("SELECT * FROM ".$table_name." WHERE post_id='$id'"),ARRAY_A);
    	echo $row['count'];
    }
    function get_content_views(){
    	global $wpdb, $id;
    	$row=$wpdb-&gt;get_row($wpdb-&gt;prepare("SELECT * FROM ".$table_name." WHERE post_id='$id'"),ARRAY_A);
    	return $row['count'];
    }

    Then I’ve placed this in my single.php file:

     
     
    			<!-- /storycontent -->

    Any ideas what I’m doing wrong?

  7. Josh
    November 13th, 2009 at 07:40 | #7

    Hmm, that last bit of code should have turned out like this:

    <div class=”storycontent”>
    <?php the_content(); update_count(); ?>
    </div><!– /storycontent –>

  8. Josh
    November 13th, 2009 at 08:02 | #8

    Nevermind, I got it fixed… I forgot to define the variable $table_name in the other two functions…

  9. February 4th, 2010 at 08:31 | #9

    Why don’t you use a filter instead of hacking the_content() core? o.O

  10. pyr0t3chnician
    February 4th, 2010 at 15:56 | #10

    If you use something, it’s better to understand how it works so you can modify it later on to get it to do what you want it to do. I in fact created my own module to display all this, but I had to figure out how to do it first to create a module. Very rarely are you going to use EVERY feature a CMS like Wordpress offers, and there are always modifications you will need to do to make it perform the operations you want. You can search for them, but like I said, rarely will they do EXACTLY what you want. If you understand how the core works, you can easily get it working the way you want.

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">
Trackbacks (0 ) Detail Trackback