Put simply, you don’t, and you shouldn’t
The Problems
Race Conditions Make the Data Super Unreliable
Updating post meta, options, terms, etc is not an atomic operation. You need to fetch the view count, add 1 to it, then send it back to the database.
During that process, another page load is occuring which does the same thing, leading to the following situation:
- user 1: get_post_meta 5!
- user 2: get_post_meta 5!
- user 1: adds 1, 6!
- user 2: adds 1, 6!
- user 1: saves update_post_meta, 6 views!
- user 2: saves update_post_meta, 6 views!
Now your counter says 6, when it should say 7.
Huge Performance Costs
Database writes are a lot more expensive than reads, and this system involves a database write on every page load. This will not scale, and will have significant performance and speed problems.
So How Do I Track Page Views?
External services and software. These kinds of systems need to be built in a particular way so that they give reliable information without being super slow. It isn’t an easy task.
So instead, use a 3rd party service, and pull that information in at regular intervals. You could make a fresh request every time you view a page to get 100% accurate data, but that would be even slower, you wouldn’t be able to cache the pages, and load times could be higher than 10 seconds, which is awful for SEO and UX.
On my own site, I pull Google Analytics data in every hour for the top 10 viewed posts, the 10 most recent, and 10 posts that have not been checked recently ( I save a timestamp for when they were last checked, and use the 10 oldest timestamps )