wordpresspost-meta

How to Show Total Post Views of User in WordPress community theme?


So, here I am using Boombox Theme for my community website and I wanna show "Total post reads/views" from a user, for example an A user has 10 post and has various views each post, I need the total view from all of A's post. is it possible to do it in wordpress platform? since what i found in my database tables, i couldn't find any related field i could "play" for.

I've tried to modify an update_post_meta function, tried to add another condition on the function.php file, but it doesn't work.

here's the function:

function boombox_update_post_total_view( $scale, $post_id ) {
    if( absint( $scale ) > 0 ) {
        $total = intval( boombox_get_post_meta( $post_id, 'total_views' ) );
        $total += $scale;

        update_post_meta( $post_id, 'total_views', $total);

    }
}

add_action( 'boombox/view_total_updated', 'boombox_update_post_total_view', 10, 2 );

and here's the database table structure: database table structure

thank you. NB: I don't even sure that I edited the correct file.


Solution

  • This will work with any theme.

    Step 1: Add this codes from the following block in your themes function.php file.

    function getPostViews($postID){
        $count_key = 'post_views_count';
        $count = get_post_meta($postID, $count_key, true);
        if($count==''){
            delete_post_meta($postID, $count_key);
            add_post_meta($postID, $count_key, '0');
            return "0 View";
        }
        return $count.' Views';
    }
    function setPostViews($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, '0');
        }else{
            $count++;
            update_post_meta($postID, $count_key, $count);
        }
    }
    // Remove issues with prefetching adding extra views
    remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
    

    Step 2: Add this line of code to single.php file. Please note that it should be inside the loop, you can add it right after the_content():

    setPostViews(get_the_ID());
    

    For example, it should be:

    the_content(); setPostViews(get_the_ID());
    

    Step 3: Add this line of code where you want to show the total of post's view:

    echo getPostViews(get_the_ID());
    

    Source: https://www.themexpert.com/blog/track-display-post-views-in-wordpress