Track Number of Visits to WordPress Pages and Posts

Almost everyone who has a WordPress site/blog, uses Google Analytics. This great tracking tool gives you insight into your visitors that traditional marketers would only dream of. Sometimes you want to do some things that Google Analytics is not a right fit for. You may want to track which pages or posts are the most popular.

Below is a function that you can put in your functions.php file.


function yab_post_view_counter($post_id) {
    $post_meta_key = 'yab_post_view_count';
    $post_views = get_post_meta($post_id, $post_meta_key, true);
    if( $post_views === '') {
        $post_views = 1;
        add_post_meta($post_id, $post_meta_key, $post_views);
        return $post_views;
    }
    $post_views++;
    update_post_meta($post_id, $post_meta_key, $post_views);
    return $post_views;
}

Once you have done this, be sure to put the yab_post_view_counter() somewhere in your post.php or page.php file. From now on, you’ll be able to call and sort all your posts by this meta value, or create a widget that shows the most popular post and/or pages. No plugins required!


Also published on Medium.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.