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.

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:

// 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 );


  1. Thanks for improving this snippet, the one on WPSnippets wasn’t quite to my liking, and I prefer your coding style (more like mine!), so I can understand it a lot quicker.

    One question – I’ve just started experimenting with custom post types for a job board I’m creating.
    Which parts do I need to swap out to make it work for my job_listing CPT? Or does it work out-of-the-box with CPTs as well?

Leave a Reply

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