Simple Post View counter for WordPress

Right now I’m working on a redesign for TexturePlanet.
Up until now I was using Detube theme on TexturePlanet, and it was really more like in an experiment stage to test if people are still looking for textures, and they are.

The Detube theme was using WP-Post-Views wordpress plugin, but folks over at WPengine didn’t like that, so they kindly pointed me to WPSnippets as a “how to update post view count”. At the moment, I’m trying to simplify simplify, so I don’t mind the technique. But the code seemed a bit too wet for my taste, so here is my take on it. It’s the same technique, I’ve just adjusted it a bit.

<?php
if ( ! defined( "POST_VIEWS_KEY" ) ) {
    define( "POST_VIEWS_KEY", "post_views_count" );
}
// function to display number of posts.
function get_post_views( $post_id ) {

    $count = get_post_meta( $post_id, POST_VIEWS_KEY, true );
    if ( $count == '' ) {
        delete_post_meta( $post_id, POST_VIEWS_KEY );
        add_post_meta( $post_id, POST_VIEWS_KEY, '0' );

        return 0;
    }

    return $count;
}

// function to count views.
function update_post_views( $post_id ) {

    $count = get_post_views( $post_id );
    $count ++;
    update_post_meta( $post_id, POST_VIEWS_KEY, $count );
}

// Add it to a column in WP-Admin
add_filter( 'manage_posts_columns', 'posts_column_views' );
add_action( 'manage_posts_custom_column', 'posts_custom_column_views', 5, 2 );
function posts_column_views( $defaults ) {

    $defaults['post_views'] = __( 'Views' );

    return $defaults;
}

function posts_custom_column_views( $column_name, $id ) {

    if ( $column_name === 'post_views' ) {
        echo get_post_views( get_the_ID() ) . __( "Views" );
    }
}

?>

The usage remains the same as instructed on WP-Snippets. You just do:

<?php
//usage
// To update view count:
update_post_views( $post->ID );
// To display view count:
$views = get_post_views( $post->ID );
printf( _n( "%d View", "%d Views", $views ), $views );
?>

Leave a Reply

Your email address will not be published. Required fields are marked *