How to count post views in wordpress without any plugin (Part 1)

Published
61
post view counting wordpress

The most widely used CMS for building websites is WordPress, which has a large user base and is relatively simple to use. In the store, we have many plugins for counting the post view of WordPress, but sometimes we want to control our data and the plugin may be too cloggy. I have a simple solution for you.

WordPress post meta

Before going to code, you need to know how WordPress store post data and its related data (we call it metadata of the post).

Post meta is the place WordPress saves additional information related to posts. A single post may have many different meta, we identify it by the meta_key.

In this post, i will use 3 wp methods: get_post_meta(), delete_post_meta(), add_post_meta() and update_post_meta(). Their purposes are similar to their names.

WordPress post meta structure

Count and display post view by post meta

1. Create two functions to get and set the post view

<span role="button" tabindex="0" data-code="
<?php
/**
 * Post view counter for catalog
 * author: codingcatalog.com
 */
function getPostView($postID)
{
    $count_key = '_post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if ($count == '') {
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, $count);
        return $count;
    }
    return $count;
}

function setPostView($postID)
{
    $count_key = '_post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if ($count == '') {
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, $count);
    } else {
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}

?>

2. We need a function to display the post view

function displayPostView(){
    $postID = get_the_ID();
    setPostView($postID);
    echo getPostView($postID);
}

3. But if we call the function to update view every time the page is reloaded, it will be very ridiculous. So we can apply the session to the user, in a session, just one view is accepted.


function register_catalog_session()
{
    if (!session_id()) {
        session_start();
    }
}

add_action('init', 'register_catalog_session');

/**
 * check if this post is viewed in the current session
 * return true is viewed, false is not.
 */
function checkSessionView($postID): bool
{
    $post_views = [];
    if (isset($_SESSION['catalog_post_views'])) {
        $post_views = $_SESSION['catalog_post_views'];
    }

    if (in_array($postID, $post_views)) {
        return true;
    } else {
        array_push($post_views, $postID);
        $_SESSION['catalog_post_views'] = $post_views;
        return false;
    }
}

4. Modify the setPostView function to use the session checker:

function setPostView($postID)
{
    // skip if viewed
    if(checkSessionView($postID)) {
        return;
    }

    $count_key = '_post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if ($count == '') {
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, $count);
    } else {
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}

You can add all the functions above to functions.php. But I recommend creating a new file inside inc folder, named post-view.php

post-view.php final content:

<span role="button" tabindex="0" data-code="
<?php
/**
 * Post view counter for catalog
 * author: codingcatalog.com
 */

function register_catalog_session()
{
    if (!session_id()) {
        session_start();
    }
}

add_action('init', 'register_catalog_session');

function displayPostView(){
    $postID = get_the_ID();
    setPostView($postID);
    echo getPostView($postID);
}

function getPostView($postID)
{
    $count_key = '_post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if ($count == '') {
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, $count);
        return $count;
    }
    return $count;
}

function setPostView($postID)
{
    // skip if viewed
    if(checkSessionView($postID)) {
        return;
    }

    $count_key = '_post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if ($count == '') {
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, $count);
    } else {
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}

/**
 * check if this post is viewed in the current session
 * return true is viewed, false is not.
 */
function checkSessionView($postID): bool
{
    $post_views = [];
    if (isset($_SESSION['catalog_post_views'])) {
        $post_views = $_SESSION['catalog_post_views'];
    }

    if (in_array($postID, $post_views)) {
        return true;
    } else {
        array_push($post_views, $postID);
        $_SESSION['catalog_post_views'] = $post_views;
        return false;
    }
}

Then open functions.php and add this line (I’m editing directly in my theme, you need to include the right directory):

include_once( get_template_directory() . '/inc/post-view.php' );

In the final step, open your content-single.php, add this line to show the view:

<span role="button" tabindex="0" data-code="<span style="padding-top:0.15em;"><?php echo displayPostView(); ?>
<span style="padding-top:0.15em;"><?php echo displayPostView(); ?></span>

Conclusion

In this post, I have shown you the way to count WordPress post views without any plugin.

In the next post, I will show how to count views in an advanced way (using ajax)

Happy coding!