I am working on a project, which requires a page visit count to be shown on the single post.

How can I do this in wordpress, I am guessing, that I have to store them in the same wordpress db?


You can use custom fields for this. What I would suggest is setting up a shortcode you can put on any page you want to show the counter. For an extremely basic example with no HTML formatting, you can do this:

add_shortcode( 'examplecounter', 'counter_shortcode' );
function counter_shortcode( $atts, $content = null ) {
    global $post;
    if( isset( $post->ID ) ) {
        $current_count = get_post_meta( $post->ID, '_counter_custom_field', true );
        $new_count = $current_count === '' ? 1 : $current_count + 1;
        update_post_meta( $post->ID, '_counter_custom_field', $new_count );
        return $new_count;

And now you can place [examplecounter] anywhere in a post and it should start counting for you. :)

  • 1
    Keep in mind that one person can reload the page x times and thus "sabotage" the counter. – Steven Feb 29 '12 at 8:13
  • Absolutely, you will want to do more than just the above to make sure that doesn't happen, such as (possibly) store a cookie that is only valid for a certain amount of time and make sure that cookie is not set in the shortcode function. That is one example of something you could do, not sure if it is the best though. – Jared Feb 29 '12 at 8:30
function k99_post_hits( $id, $action ) {
        $k99_HitMetaField   = '_k99_post_hits'; // Your Custom field that stores the views
        $k99_PostHits   = get_post_meta($id, $k99_HitMetaField, true);
        switch ($action) {
        case 'count' :
        if ( $k99_PostHits =='' ) {
            $k99_PostHits = mt_rand(200,950); //debug joke
            delete_post_meta( $id, $k99_HitMetaField);
            add_post_meta( $id, $k99_HitMetaField, $k99_PostHits );
            update_post_meta( $id, $k99_HitMetaField, $k99_PostHits );
        case 'display' :
        echo 'this page was viewed: ' , $k99_PostHits ;

Edit I: neewbie note - forgot to explain how to use :

Put this in the page you want to count, preferably before anything else but inside the loop.

<?php k99_post_hits( $post->ID, 'count' );  //adding post counter?>

Put the next line where you want to display the count :

<?php k99_post_hits( $post->ID, 'display' );  //adding post counter display ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.