Build a Headless View Tracking System with Init View Count

This guide shows you how to use the Init View Count plugin in a headless WordPress setup to track and display post views using JavaScript and REST API. Ideal for projects using React, Next.js, Vue, or any frontend framework that interacts with WordPress via API.

Build a Headless View Tracking System with Init View Count

1. Enable REST API Endpoints

Init View Count exposes two endpoints:

  • POST /wp-json/initvico/v1/count: increase view count for a post
  • GET /wp-json/initvico/v1/top: retrieve the most viewed posts

Ensure permalinks are enabled and WordPress REST API is accessible in your environment.

2. Send a View Count Request

When a user lands on a post page, send a request to increase the view count using JavaScript. You should delay the call until the user is likely reading.

// Assume "postId" is the ID of the current post
setTimeout(() => {
  if (!postId) return;

  fetch('https://yourdomain.com/wp-json/initvico/v1/count', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ post_id: postId })
  });
}, 3000); // Only count after 3 seconds

You can enhance this with scroll detection or user interaction.

3. Display View Count in the Frontend

To show the number of views on a post page, you can use a custom endpoint or call the /top API and filter by post ID.

async function getViews(postId) {
  const res = await fetch('https://yourdomain.com/wp-json/initvico/v1/top?fields=full&number=1&post_type=post');
  const data = await res.json();
  const post = data.find(item => item.id === postId);
  return post ? post.views : 0;
}

Alternatively, you can expose a custom REST endpoint that returns the current view count of a single post using the same logic used in the plugin’s shortcode.

4. Optional: Show Time Since Published

If you want to display “Posted 3 days ago”, you can calculate it on the frontend using the date field returned from /top or another API.

function timeAgo(dateString) {
  const date = new Date(dateString);
  const now = new Date();
  const diff = Math.floor((now - date) / 1000);
  if (diff < 60) return `${diff} seconds ago`;
  if (diff < 3600) return `${Math.floor(diff / 60)} minutes ago`;
  if (diff < 86400) return `${Math.floor(diff / 3600)} hours ago`;
  return `${Math.floor(diff / 86400)} days ago`;
}

5. Recommended Enhancements

  • Use sessionStorage or localStorage to prevent duplicate count submissions
  • Debounce the counting logic with scroll or delay
  • Use tools like SWR or TanStack Query to cache view data efficiently

6. Summary

Init View Count can be fully integrated into headless or decoupled frontend applications via its REST API. This approach gives you control over when and how views are counted, while still benefiting from server-side tracking and filtering flexibility.

Comments


  • No comments yet.

Init Toolbox

Press Ctrl + \ on desktop, or swipe left anywhere on mobile.

Login