Adding and displaying post view counts in WordPress and Bricks Builder is a great way to measure the popularity of your content and engage your audience. By tracking how many times each post is viewed, you can gain valuable insights into which topics resonate most with your readers.

First step is to add this function to snippet plugin or functions.php file in theme child folder:

The setPostViews function increments the view count of a specific post identified by $postID. It retrieves the current view count from the post’s metadata ‘post_views_count’ using get_post_meta. To prevent counting multiple views within the same session, it uses a session variable $_SESSION[$session_key] to track if the post view has already been counted.

Add last function below to run the setPostViews to each single post loaded:

// Hook into WordPress to set post views on post load
function increment_post_views_on_post_load($post)
{
    if (!is_single()) {
        return;
    }

    if (!empty($post->ID)) {
        setPostViews($post->ID);
    }
}
add_action('the_post', 'increment_post_views_on_post_load');
  1. Check if It’s a Single Post: The function first checks if the current page is a single post page using is_single(). If it’s not (for example, if it’s a homepage or a category page), the function stops and does nothing.
  2. Get the Post ID: If it is a single post page, the function checks if the post has a valid ID. The post ID is a unique number that identifies each post.
  3. Count the View: If the post ID is valid, the function calls another function, setPostViews, and passes the post ID to it. This function updates the view count for the post.

The line add_action('the_post', 'increment_post_views_on_post_load') tells WordPress to run the increment_post_views_on_post_load function every time a post is loaded. This ensures that the view count is updated each time someone looks at a post.

To get the post count, add this function:

Finally to display the post count in loop in wordpress template use this code:

// WordPress general
echo getPostViews(get_the_ID());

To display the post count in Bricks Builder dynamic data, use this:

cf_post_views_count